Reputation: 12904
I have recently become involved in a large project and I have very little experience of Unity and IOC/DI and I am looking for clarification on how instances are created when defined in a Unity container.
Given the following pieces of code;
//Unity Configuration
container.RegisterAsSingleton<IService, Service>();
//References in base controller class
private readonly IService _Service;
protected DefaultController(IService Service)
{
_Service = Service;
}
protected string UseService(string id)
{
return _Service.Method(id);
}
Do I need to initialise an instance using something similiar (in an MVC solution) to;
_Service = DependencyResolver.Current.GetService<IService>()
;
or would an instance be created when the Service method is called first time?
_Service.Method(id);
I am trying to figure out the best place to put this code if required.
Upvotes: 0
Views: 105
Reputation: 6023
I can't tell for sure of course, but usually an MVC project using DI is wired up in a way that the DI container is not only used to create the IService instance, but also the DefaultController that depends on IService.
The MVC framework has extension points you can use to provide your own construction logic, for instance using a DI container like Unity or Windsor. If your project already uses DI, it is probably already setup that way.
So if everything is wired up correctly (DI container creates the controller, IService is registered to the DI container), the IService dependency is injected into the DefaultController constructor. You shouldn't have to do anything, IService should already be created when the controller method is called.
Upvotes: 1