I have a wrapper on ModelStateDictionary which all my services accept. Is it possible to configure the autofac to inject the controller ModelStateDictionary into the constructor of the wrapper and then inject it into service constructor?
//code
public class ModelValidation : IModelValidation {
public ModelValidation(ModelStateDictionary msd){...}
..
..
}
public class CustomerService{
public CustomerService(IModelValidation mv){...}
..
}
Thanks
Based on your comments I hereby revise my answer 🙂
ModelStateDictionaryis clearly not a service that should be resolved by the container, but rather data that should be provided at instantiation time. We can tell that from the fact that ModelState is owned by each Controller instance and is thus not available to the container at “resolve time”.Furthermore, each
ModelValidationinstance will be bound to aModelStateDictionaryinstance and is thus also to be considered as data.In Autofac, when data must be passed to constructors (optionally in addition to other dependencies), we must use factory delegates. These delegates will handle dependency and data passing to the constructor. The sweet thing with Autofac is that these delegates can be autogenerated.
I propose the following solution:
Since both ModelValidation and CustomerService requires data in their constructors, we need two factory delegates (note: the parameter names must match the names in their corresponding constructor):
Since your controllers shouldn’t know where these delegates comes from they should be passed to the controller constructor as dependencies:
The CustomerService should have a constructor similar to this (optionally handle some of this in a ServiceBase class):
To make this happen we need to build our container like this:
So, when the controller is resolved (eg when using the MvcIntegration module), the factory delegates will be injected into the controllers and services.
Update: to cut down on required code even more, you could replace
CustomerServiceFactorywith a generic factory delegate like I’ve described here.