将ModelState传递给业务层

时间:2013-10-15 16:16:13

标签: c# asp.net-mvc

我正在使用ASP.NET MVC网站,我们正在利用DI将必要的组件注入我们的控制器。

我目前面临的挑战是我想将服务提供者注入控制器并将“UserRequestContext”对象注入服务提供者。

UserRequestContext对象封装了当前用户ID,电子邮件地址,角色,并且还传递了modelstate对象(或者至少,我希望它)。我想在我的服务提供者层执行所有验证操作。

问题当然是我的服务提供者对象必须在控制器之前被实例化,并且因为ModelState在创建控制器之前不存在,所以我无法创建UserRequestContext对象。

我的目标是消除将IUserRequestContext对象传递给IServiceProvider的每个方法的需要。

而不是: void ServiceProvider.CreateUser(User user,IUserRequestContext userRequestContext);

使用此: void ServiceProvider.CreateUser(用户用户)

以下是我此时编写的代码:

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
}

1 个答案:

答案 0 :(得分:0)

我没有看到任何错误。我在我的代码中遵循了一个非常相似的模式。

我创建了一个IModelState接口,我将其传递到我的服务中。我为ModelStateDictionary创建了一个扩展方法,将其封装到实现接口的帮助类中。我现在可以这样做:

public class mycontroller
{
    private readonly IService _service;

...

    public ActionResult myaction()
    {
        _service.dowork(ModelState.ToWrapper())
 ....
相关问题