gpt4 book ai didi

c# - unity RegisterInstance IDisposable对象

转载 作者:太空狗 更新时间:2023-10-29 17:52:36 24 4
gpt4 key购买 nike

统一 2.0:

默认情况下 RegisterInstance 使用 ContainerControlledLifetimeManager。当 Unity 容器被释放时,它会在实例上调用 Dispose(如果 IDisposable)。

在我的情况下,这不是我想要的。该实例由另一个类拥有和处置; Unity 应该只注入(inject)引用。所以我用了:

container.RegisterInstance(instance, new ExternallyControlledLifetimeManager());

Unity 文档(在 Understanding Lifetime Managers 下)指出:

Using the RegisterInstance method to register an existing object results in the same behavior as if you just registered the lifetime container with RegisterType. Therefore, it is recommended that you do not use the RegisterInstance method to register an existing object when using the non-default lifetime managers except for the thread in which the RegisterInstance was invoked.

这是什么意思?

同一节还指出:

If you registered an existing instance of an object using the RegisterInstance method, the container returns the same instance for all calls to Resolve or ResolveAll or when the dependency mechanism injects instances into other classes, provided that one of the following is true:

  • You have specified a container-controlled lifetime manager
  • You have used the default lifetime manager
  • You are resolving in the same context in which you registered the instance when using a different lifetime manager.

在将 RegisterInstance 与 ExternallyControlledLifetimeManager 一起使用后,我尝试在不同的线程中解析,它成功了 - 我得到了单例实例。

我的代码与创建实例注册部分中的示例匹配。不过,我想确保我理解上下文警告。

需要明确的是,我始终希望 Unity 容器注入(inject)我注册的实例,而不考虑线程等,而且我希望 Unity 处理它。我这样做正确吗?

最佳答案

注意 ExternallyControlledLifetimeManager。您仍然必须在容器外部某处保存对实例的引用。一旦失去引用,您就会失去实例,因为 ExternallyControlledLifetimeManager 只持有 WeakReference。如果您没有正常的引用,垃圾收集器可以收集您的实例。检查example在我的博客上。

关于c# - unity RegisterInstance IDisposable对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5330639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com