简体   繁体   中英

Passing ModelState to Business Layer

I am working with an ASP.NET MVC web site and we are utilizing DI to inject the necessary components into our controllers.

The challenge I have at present is I want to inject the service provider into the controller and have a "UserRequestContext" object injected into the service provider.

The UserRequestContext object encapsulates the current users Id, email address, roles and also passes along the modelstate object (or at least, I would like it to). I want to perform all validation operations in my service provider layer.

The problem of course, is that my service provider object must be instantiated before the controller and because ModelState does not exist until the controller is created, I cannot create the UserRequestContext object.

My goal here is to eliminate the need to pass in an IUserRequestContext object to every method of the IServiceProvider.

Instead of this: void ServiceProvider.CreateUser(User user, IUserRequestContext userRequestContext);

Use this: void ServiceProvider.CreateUser(User user)

Here is the code I've worked up at this point:

public class HomeController
{       
    public HomeController(IServiceProvider provider)
    {
        _provider = provider;
    }

    private IServiceProvider _provider;
}

public class ServiceProvider : IServiceProvider
{
    private IUserRequestContext _userRequestContext;

    public ServiceProvider(IUserRequestContext userRequestContext)
    {
        _userRequestContext = userRequestContext;
    }
}

public class UserRequestContext : IUserRequestContext
{
   private ModelStateDictionary _modelState;

   public UserRequestContext(ModelStateDictionary modelState)
   {
       _modelState = modelState;
   }

   public void AddError(string key, string errorMessage)
   {
       _modelState.AddModelError(key, errorMessage);
   }

   // the rest removed for brevity
}

I don't see anything wrong with this. I've followed a very similar pattern in my code.

I created an IModelState interface that I passed into my service. I created an extension method for ModelStateDictionary that encapsulated it into a help class that implemented the interface. I could now do this:

public class mycontroller
{
    private readonly IService _service;

...

    public ActionResult myaction()
    {
        _service.dowork(ModelState.ToWrapper())
 ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM