简体   繁体   中英

Why “resolve” method always calls the class constructor that is already registered in Unity?

I use Unity and Prism in my WPF application. I have a class that is registered to the Container in the Bootstrapper in this way:

Container.RegisterType<MyClass>();

The class has a constructor has ILoggerFacade interface as a parameter:

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?

If you doesn't want your component to be instancied at each resolve, you need to declare its lifetime as 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

Unity uses the transient lifetime manager by default (when you do not specify another lifetime manager). The transient lifetime manager will give you a NEW instance of the registered type each time you call resolve. There are other lifetime managers that can be specified during registration that will provide different behavior (singleton, etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM