如何检查Unity容器是否已经解析了单例类型?

发布于 2024-12-10 05:13:44 字数 603 浏览 0 评论 0原文

给定以下统一配置:

<register type="MyProgram.IListDetailsView, MyProgram"
            mapTo="MyProgram.ListDetailsView, MyProgram"
            name="Contacts List">
    <lifetime type="singleton"/>
</register>

我想按如下方式检查代码:

bool firstCall = !container.ContainsInstance("Contacts List"))

IListDetailsView  listDetailsView = container.Resolve<IListDetailsView>("Contacts List");

if(firstCall)
{  
// do some work on listDetailsView
}

是否有与此(组成的)ContainsInstance 方法等效的方法或其他方式来获取此状态数据?我想检查 Unity 引用一个实例,而不是检查该类型是否已注册。

Given the following unity configuration:

<register type="MyProgram.IListDetailsView, MyProgram"
            mapTo="MyProgram.ListDetailsView, MyProgram"
            name="Contacts List">
    <lifetime type="singleton"/>
</register>

I want to do a check in code as follows:

bool firstCall = !container.ContainsInstance("Contacts List"))

IListDetailsView  listDetailsView = container.Resolve<IListDetailsView>("Contacts List");

if(firstCall)
{  
// do some work on listDetailsView
}

Is there an equivalent to this (made up) ContainsInstance method or some other way to get this state data? I want to check Unity references an instance, not that the type has been registered.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

染火枫林 2024-12-17 05:13:44

那么我建议你做错了什么。 UI 组件应根据需要创建和销毁。如果您确实需要执行此操作,请使用一个静态布尔值来指示您的“执行一次”代码是否已运行。再次在构造函数中执行此操作。如果您需要确保线程安全,则需要锁定构造函数。或者,您可以在静态构造函数中对视图详细信息进行操作; .Net 将确保仅在您第一次访问任何静态成员时运行一次。

I suggest then that you're doing something wrong. UI components should be created and destroyed as needed. If you really need to do this, then have a static boolean that indicates if your "do once" code has been run. Again, do this in the constructor. You'll need to lock in the constructor though if you need to ensure thread safety. Alternately, you can do work in the static ctor for your view details; .Net will ensure that is only run once the first time you access any static member.

记忆で 2024-12-17 05:13:44

我希望我没有误解你的要求。但对我来说,您似乎想知道何时创建视图实例来执行一些初始化工作。这通常是使用构造函数完成的。

你将你的观点表达为团结。这不会创建视图的实例。针对视图类型的第一个解析请求使 Unity 创建视图的新实例。因此,在视图初始化期间您需要做的所有事情都可以在构造函数内完成。

I hope I didn't misunderstand your requirement. But for me it seems that you want to knwo when a view instance get's created to perform some initialization work. This is usually done using the constructor.

You register your view to unity. This does not create an instance of the view. The first resolve request for the type of the view makes unity create a new instance of the view. So all you have to do during the initializtation of the view can be done inside the constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文