English 中文(简体)
How to pass controller s ModelState to my service constructor with Autofac?
原标题:

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 :)

ModelStateDictionary is 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 ModelValidation instance will be bound to a ModelStateDictionary instance 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):

public delegate IModelValidation ModelValidationFactory(ModelStateDictionary msd);
public delegate CustomerService CustomerServiceFactory(ModelStateDictionary msd);

Since your controllers shouldn t know where these delegates comes from they should be passed to the controller constructor as dependencies:

public class EditCustomerController : Controller
{
    private readonly CustomerService _customerService;

    public EditCustomerController(CustomerServiceFactory customerServiceFactory
        /*, ...any other dependencies required by the controller */
          )
    {
        _customerService = customerServiceFactory(this.ModelState);
    }

}

The CustomerService should have a constructor similar to this (optionally handle some of this in a ServiceBase class):

public class CustomerService
{
    private readonly IModelValidation _modelValidation;

    public CustomerService(ModelStateDictionary msd,
              ModelValidationFactory modelValidationFactory)
    {
        _modelValidation = modelValidationFactory(msd);
    }

To make this happen we need to build our container like this:

var builder = new ContainerBuilder();

builder.Register<ModelValidation>().As<IModelValidation>().FactoryScoped();
builder.Register<CustomerService>().FactoryScoped();

builder.RegisterGeneratedFactory<ModelValidationFactory>();
builder.RegisterGeneratedFactory<CustomerServiceFactory>();

builder.Register<EditCustomerController>().FactoryScoped();

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 CustomerServiceFactory with a generic factory delegate like I ve described here.

问题回答
Builder.RegisterInstance(new ModelStateDictionary()).SingleInstance();
            builder.Register(c => new SW.PL.Util.ModelStateWrapper
(c.Resolve<ModelStateDictionary>())).As<IValidationDictionary>().InstancePerHttpRequest(); 

Add a new constructor without ValidationService. Assign the ValidationService by using a property.

The property must be implemented in the interface ICostumerService

public class ModelStateWrapper: IValidationDictionary {  
public ModelStateWrapper(ModelStateDictionary msd){}
}

public class CustomerService: ICostumerService{
public IValidationDictionary ValidationDictionary { get; set; }
public CustomerService(ICustomerRepsitory customerRepository, IValidationDictionary validationDictionary ){} 
public CustomerService(ICustomerRepsitory customerRepository){}
}

public Controller(ICustomerService customerService)
{
  _customerService= menuService;
  _customerService.ValidationDictionary = new ModelStateWrapper(this.ModelState);
  _customerService= sportsService;
}




相关问题
WebForms and ASP.NET MVC co-existence

I am trying to make a WebForms project and ASP.NET MVC per this question. One of the things I ve done to make that happen is that I added a namespaces node to the WebForms web.config: <pages ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

Create an incremental placeholder in NHaml

What I want to reach is a way to add a script and style placeholder in my master. They will include my initial site.css and jquery.js files. Each haml page or partial can then add their own required ...

asp.net mvc automapper parsing

let s say we have something like this public class Person { public string Name {get; set;} public Country Country {get; set;} } public class PersonViewModel { public Person Person {get; ...

structureMap mocks stub help

I have an BLL that does validation on user input then inserts a parent(PorEO) and then inserts children(PorBoxEO). So there are two calls to the same InsertJCDC. One like this=>InsertJCDC(fakePor)...

ASP.NET MVC: How should it work with subversion?

So, I have an asp.net mvc app that is being worked on by multiple developers in differing capacities. This is our first time working on a mvc app and my first time working with .NET. Our app does not ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

热门标签