Search code examples
asp.net-mvcdependency-injectionunity-containerconstructor-injection

Dynamically injecting constructor parameters using Unity


I'm using the Unity container for dependency injection in an ASP.NET MVC 4 application.

For a particular controller (say ProductController), I have an dependency injection scenario as follows:

  1. The ProductController constructor takes a IProductsRepository instance.
  2. The IProductsRepository implementation has a constructor that accepts a IProductsService instance.
  3. The IProductsService implementation has a constructor that accepts an authentication token string, which is retrieved from a cookie in the web request.

What's the correct way to do automatic dependency injection in this scenario, considering that the authentication token cookie can only be retrieved after the controller instance has been created?


Solution

  • If you need to delay the creation of the ProductService you can

    • Inject a custom factory for that service
    • Let the DI container auto-generate a delegate factory of Type Func<IProductService> and inject that delegate into your controller
    • Let the container generate a lazy proxy that hides the delayed creation of your service from the consumer

    I prefer the third alternative as it is completely transparent for the consumers of IProductService