Val*_*yev 5 asp.net-mvc autofac
我在ModelStateDictionary上有一个包装器,我的所有服务都接受它.是否可以配置autofac将控制器ModelStateDictionary注入包装器的构造函数,然后将其注入服务构造函数?
//code
public class ModelValidation : IModelValidation {
public ModelValidation(ModelStateDictionary msd){...}
..
..
}
public class CustomerService{
public CustomerService(IModelValidation mv){...}
..
}
Run Code Online (Sandbox Code Playgroud)
谢谢
根据您的意见,我特此修改我的答案:)
ModelStateDictionary
显然不是应该由容器解决的服务,而是应该在实例化时提供的数据.我们可以告诉我,ModelState由每个Controller实例拥有,因此在"解析时"不可用于容器.
此外,每个ModelValidation
实例将绑定到一个ModelStateDictionary
实例,因此也被视为数据.
在Autofac中,当必须将数据传递给构造函数时(可选地除了其他依赖项之外),我们必须使用工厂委托.这些委托将处理传递给构造函数的依赖项和数据.Autofac的好处在于这些代表可以自动生成.
我提出以下解决方案:
由于ModelValidation和CustomerService都需要构造函数中的数据,因此我们需要两个工厂委托(注意:参数名称必须与其相应构造函数中的名称匹配):
public delegate IModelValidation ModelValidationFactory(ModelStateDictionary msd);
public delegate CustomerService CustomerServiceFactory(ModelStateDictionary msd);
Run Code Online (Sandbox Code Playgroud)
由于您的控制器不应该知道这些委托来自何处,因此它们应该作为依赖项传递给控制器构造函数:
public class EditCustomerController : Controller
{
private readonly CustomerService _customerService;
public EditCustomerController(CustomerServiceFactory customerServiceFactory
/*, ...any other dependencies required by the controller */
)
{
_customerService = customerServiceFactory(this.ModelState);
}
}
Run Code Online (Sandbox Code Playgroud)
CustomerService应该有一个与此类似的构造函数(可选择在ServiceBase类中处理其中的一些):
public class CustomerService
{
private readonly IModelValidation _modelValidation;
public CustomerService(ModelStateDictionary msd,
ModelValidationFactory modelValidationFactory)
{
_modelValidation = modelValidationFactory(msd);
}
Run Code Online (Sandbox Code Playgroud)
为了实现这一点,我们需要像这样构建我们的容器:
var builder = new ContainerBuilder();
builder.Register<ModelValidation>().As<IModelValidation>().FactoryScoped();
builder.Register<CustomerService>().FactoryScoped();
builder.RegisterGeneratedFactory<ModelValidationFactory>();
builder.RegisterGeneratedFactory<CustomerServiceFactory>();
builder.Register<EditCustomerController>().FactoryScoped();
Run Code Online (Sandbox Code Playgroud)
因此,当控制器被解析时(例如,当使用MvcIntegration模块时),工厂代表将被注入控制器和服务.
更新:为了减少所需的代码,您可以替换CustomerServiceFactory
为我在此处描述的通用工厂代理.
归档时间: |
|
查看次数: |
3133 次 |
最近记录: |