Reputation: 3336
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.
Upvotes: 1
Views: 2176
Reputation: 107247
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, i.e.
// 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 (i.e. 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 (i.e. this smells a bit like the object has an assumed 'lifecycle' to it)
Upvotes: 3