asp.net-mvc-4 - mvc 过滤器中的依赖注入(inject)是全局的

标签 asp.net-mvc-4 dependency-injection asp.net-mvc-5

我使用unity,然后在mvc4、mvc5中进行ninject。 我通过这种方式将服务或 dbcontext 作为公共(public)属性注入(inject)到操作过滤器中:

 public class MyActionFilterAttribute: FilterAttribute,IActionFilter
{
    [Inject]
    public IDbContext DbContext { get; set; }
    [Inject]
    public IProductService ProductService { get; set; }


    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Debug.WriteIf(DbContext == null, "db context is null");
        Debug.WriteIf(ProductService == null, "productservice is null");


    }
    public void OnActionExecuted(ActionExecutedContext filterContext)
    { }
}

}

如果我注册全局过滤器,filters.Add(new MyActionFilterAttribute()); DbContext 和 ProductService 始终为 null。 但如果我将 [MyActionFilter] 属性标记为 Controller ,则一切正常。 我想将一些过滤器注册为全局过滤器,请帮忙。

最佳答案

当您注册像这样的全局过滤器时,您正在注册过滤器实例。每次调用都会使用同一个实例。此实例没有填充您的依赖项,因为您是使用默认构造函数自行创建的,而不是从容器中解析它。当然,您无法在全局过滤器注册期间解析过滤器的实例,因为您的依赖项(例如 DbContext)需要根据请求确定范围。

所以你有 4 个选择。

  • 使用操作过滤器装饰所有 Controller
  • 创建 Controller 基类,使用操作过滤器装饰此类,然后从此类派生所有 Controller 。
  • 在操作过滤器代码中使用某种形式的服务定位器,以便在每次需要时从容器中解析依赖项。然后您可以将您的过滤器注册为全局过滤器。
  • 创建自定义 IFilterProvider 并在 GetFilters 方法中从容器解析您的过滤器。然后注册您的提供程序 FilterProviders.Providers.Add(new MyFilterProvider(diContainer));

关于asp.net-mvc-4 - mvc 过滤器中的依赖注入(inject)是全局的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34330638/

相关文章:

asp.net-mvc - 使用 MVVM 将 kendo.data.DataSource 绑定(bind)到组合

c# - ActionLink 不区分两个不同的相似路由

authentication - DotNetOpenAuth 的工作原理

c# - 循环依赖的依赖注入(inject)

c# - CaSTLe windsor 3.0 和 ASP.NET MVC Controller

visual-studio-2013 - 脚手架 Controller 不适用于 Visual Studio 2013 update 2

asp.net-mvc-routing - 如何设置不使用属性路由路由的 Controller 方法

asp.net-mvc-4 - 在 MVC4.5 中将公共(public)数据传递给 _layout.cshtml 的模式

c# - ASP.NET MVC 5 模型绑定(bind)列表为空

javascript - 将特定值注入(inject)对象构造函数