1

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,

www.sitename.com/Home

or

www.sitename.com/Home/News

4

1 回答 1

1

You should let ASP .NET MVC know that you're using StructureMap for dependency injection.

You can do it by providing an IControllerFactory

Before wiring the routing (in the begining of your program) use this code-

ControllerBuilder.Current.SetControllerFactory(new StractureMapControllerFactory());

Where StructureMapControllerFactory will provide the implementation to use the DI container when instantiating Controllers

I've never done it with StructureMap but I guess someone has already implemented the ContorllerFactory for StructureMap.

于 2012-11-25T19:09:56.280 回答