相关疑难解决方法(0)

ASP.Net MVC 4 Custom ValidationAttribute依赖注入

在我目前正在开发的ASP.Net MVC 4应用程序中,有许多具有仓库属性的模型.我希望所有这些模型都有验证,以确保输入的仓库是有效的仓库.看起来最简单的方法是使用自定义ValidationAttribute类.然后验证代码将被集中,我可以将属性添加到每个模型中的属性.

我需要调用一个服务来确保仓库是一个有效的仓库.我有一个代表此服务的接口,我使用Ninject在我使用此服务的应用程序中执行依赖注入.这样我可以使用模拟并轻松地对应用程序进行单元测试.

我希望我的自定义ValidationAttribute类在使用此服务时使用依赖注入.这是我创建的类:

public class MustBeValidWarehouse : ValidationAttribute
{
  public override bool IsValid(object value)
  {
    if (value is string)
    {
      string warehouse = value.ToString();
      NinjectDependencyResolver depres = new NinjectDependencyResolver();
      Type inventServiceType = typeof(IInventService);
      IInventService inventserv = depres.GetService(inventServiceType) as IInventService;
      return (inventserv.GetWarehouses().Where(m => m.WarehouseId == warehouse).Count() != 0);

    }
    else
    {
      return false;
    }
  }
}


public class NinjectDependencyResolver : IDependencyResolver
{
    private IKernel kernel;
    public NinjectDependencyResolver()
    {
        kernel = new StandardKernel();
        AddBindings();
    }

    public object GetService(Type serviceType)
    { …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc unit-testing dependency-injection

11
推荐指数
1
解决办法
4109
查看次数