Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将ModelState传递给业务层_C#_Asp.net Mvc - Fatal编程技术网

C# 将ModelState传递给业务层

C# 将ModelState传递给业务层,c#,asp.net-mvc,C#,Asp.net Mvc,我正在使用ASP.NET MVC网站,我们正在利用DI将必要的组件注入控制器 我目前面临的挑战是,我希望将服务提供者注入控制器,并将“UserRequestContext”对象注入服务提供者 UserRequestContext对象封装了当前用户Id、电子邮件地址、角色,还传递了modelstate对象(或者至少,我希望这样)。我想在我的服务提供者层中执行所有验证操作 当然,问题是我的服务提供者对象必须在控制器之前实例化,并且因为在创建控制器之前ModelState不存在,所以我无法创建User

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

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

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

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

这里我的目标是消除向IServiceProvider的每个方法传递IUserRequestContext对象的需要

与此相反: void ServiceProvider.CreateUser(用户用户,IUserRequestContext用户请求上下文)

使用以下命令: 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
}

我看不出这有什么问题。我在代码中遵循了一种非常相似的模式

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

public class mycontroller
{
    private readonly IService _service;

...

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