简体   繁体   中英

Is it possible to call an initialization method when singleton is created?

Is it possible to automatically call an initialization method when a singleton is created? I am thinking Unity might have some kind of way of doing this.

Right now I am doing something like this:

Container.RegisterType<IMyService, MyService >(new ContainerControlledLifetimeManager());
Container.Resolve<IMyService>().Initialize();

Where the service looks like this:

class MyService : IMyService 
{
    public void Initialize() 
    {
    }
}

Which is not ideal. I wish I could avoid calling Container.Resolve<IMyService>() which only creates the object just so I can call Initialize() on it. And since this is called at app creation time, it hurts app start time.

Although not really in the spirit of Dependency Injection, it is also possible to create your dependency object manually, run any post creation initialization steps on it, and then register the 'usable' object in the container with RegisterInstance .

Since you say MyService is a singleton, you can register just the one instance:

 var myService = new MyService(<ctor parameters go here>);
 myService.Initialize();
 Container.RegisterInstance<IMyService>(myService);

If MyService itself has complex constructor dependencies that you would like resolved, you could use Unity as a service locator during bootstrap, ie

 // NB : Resolve the concrete type, not the interface
 var myService = Container.Resolve<MyService>();
 // 'Fix' the instance.
 myService.Initialize();
 // Register via Interface
 Container.RegisterInstance<IMyService>(myService);

In the more general case (ie where a single MyService instance cannot be shared), you would need to register a factory, so that the Initialize method can be called on each new instance:

container.RegisterType<IMyService>(new InjectionFactory(c =>
{
    var transient = c.Resolve<MyService>();
    transient.Initialize();
    return transient;
}));

However, as per @Sandy's comment, something seems amiss with the design of class MyService , in that after creating the object (with it's constructor having been called), that the object is still not in a state where it can be used until 'Initialize' has been called (ie this smells a bit like the object has an assumed 'lifecycle' to it)

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