Suppose we have a controller in MVC,like to this:
public class HomeController : Controller
{
IProductService _productService;
ICategoryService _categoryService;
IUnitOfWork _uow;
public HomeController(IUnitOfWork uow, IProductService productService, ICategoryService categoryService)
{
_productService = productService;
_categoryService = categoryService;
_uow = uow;
}
// ...
}
we use StructureMap for Dependency Injection,and now in Global..asax.cs we have a code like to this:
...
ObjectFactory.Initialize(x =>
{
x.For<IUnitOfWork>().HttpContextScoped().Use(() => new EFCodeFirstContext());
x.ForRequestedType<ICategoryService>().TheDefaultIsConcreteType<EfCategoryService>();
x.ForRequestedType<IProductService>().TheDefaultIsConcreteType<EfProductService>();
});
...
Now my Question is:
for example what time a instance of EfCategoryService be created and assigned to _categoryService?
1- any time we use _categoryService in any method in this controller?
OR
2-Immediately when a request to this controller sended? for example,
or
You should let ASP .NET MVC know that you’re using StructureMap for dependency injection.
You can do it by providing an
IControllerFactoryBefore wiring the routing (in the begining of your program) use this code-
Where
StructureMapControllerFactorywill provide the implementation to use the DI container when instantiating ControllersI’ve never done it with StructureMap but I guess someone has already implemented the ContorllerFactory for StructureMap.