Reputation: 43
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:
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?
Upvotes: 4
Views: 3108
Reputation: 6806
If you need to delay the creation of the ProductService
you can
Func<IProductService>
and inject that delegate into your controllerI prefer the third alternative as it is completely transparent for the consumers of IProductService
Upvotes: 2
Reputation: 39898
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.
Upvotes: 1