[英]Why “resolve” method always calls the class constructor that is already registered in Unity?
I use Unity and Prism in my WPF application. 我在WPF应用程序中使用Unity和Prism 。 I have a class that is registered to the
Container
in the Bootstrapper in this way: 我有一个以这种方式在Bootstrapper中注册到
Container
的类:
Container.RegisterType<MyClass>();
The class has a constructor has ILoggerFacade
interface as a parameter: 该类具有一个构造函数,该构造函数具有
ILoggerFacade
接口作为参数:
private ILoggerFacade _logger;
public MyClass(ILoggerFacade logger)
{
_logger = logger;
//do some stuff
}
When I try to resolve that class instance, I realized that class constructor is called while returning the instance. 当我尝试解析该类实例时,我意识到返回实例时会调用类构造函数。 So, all stuff is done from scratch.
因此,所有工作都是从头开始的。 I resolve the instance this way:
我以这种方式解析实例:
MyClass a = Container.Resolve<MyClass>();
What is the reason behind calling constructor each Resolve method I execute? 在我执行的每个Resolve方法中调用构造函数的原因是什么?
If you doesn't want your component to be instancied at each resolve, you need to declare its lifetime as ContainerControlled : 如果您不希望每次解析都实例化组件,则需要将其生命周期声明为ContainerControlled:
myContainer.RegisterType<MySingletonObject>(new ContainerControlledLifetimeManager());
see https://msdn.microsoft.com/en-us/library/dn178463%28v=pandp.30%29.aspx#sec34 but be careful of side effects, as your object will behave like a singleton 请参阅https://msdn.microsoft.com/zh-cn/library/dn178463%28v=pandp.30%29.aspx#sec34,但请注意副作用,因为您的对象的行为就像单例一样
Unity uses the transient lifetime manager by default (when you do not specify another lifetime manager). 默认情况下(当您不指定其他寿命管理器时),Unity使用过渡寿命管理器。 The transient lifetime manager will give you a NEW instance of the registered type each time you call resolve.
每次调用resolve时,过渡生命周期管理器都会为您提供一个已注册类型的新实例。 There are other lifetime managers that can be specified during registration that will provide different behavior (singleton, etc.)
在注册期间可以指定其他寿命管理器,这些管理器将提供不同的行为(单例等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.