Question

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?

Was it helpful?

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

OTHER TIPS

I think you have two options:

1 Use container.Resolve() and pass the parameter when it's available.

So instead of asking for the IProductsService in the constructor of your ProductsRepository you do something like this:

IProductsService anInstance = container.Resolve<IProductsService>(new ParameterOverride("authenticationTokenString", "myValue"));

This is called a ParameterOverride. The MSDN documentation can be found here: Resolving Objects by Using Overrides

2 Instead of passing the plain authentication token string, encapsulate this behind an interface and pass that one. Your IProductsService will take a IAuthenticationTokenProvider and will ask that class for the required token. Your implementation will access the required objects after they are created to get the correct values.

I would choose for option two. It will keep your design cleaner and let Unity handle all dependency injection without any manual work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top