将依赖项注入MVC​​3过滤器

时间:2011-12-24 04:55:55

标签: asp.net-mvc-3 ninject

我一直在尝试将依赖项注入自定义授权过滤器。

OutletService (这是我试图注入我的过滤器的服务)

public class OutletService : IOutletService
{
    #region Fields

    private readonly IRepository<Outlet> _outletRepository;

    #endregion

    #region Ctor

    public OutletService(IRepository<Outlet> outletRepository)
    {
        _outletRepository = outletRepository;
    }

    #endregion

    // Rest of class omitted 

CustomAuthorizeAttribute (部分,此示例的名称也已更改)

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    private IOutletService _outletService;
    private IModuleService _moduleService;

    public string Action { get; set; }
    public int Level { get; set; }

    public MarcusAuthorizeAttribute()
    {

    }
    [Inject]
    public MyAuthorizeAttribute(IOutletService outletService, IModuleService moduleService)
    {
        _outletService = outletService;
        _moduleService = moduleService;
    }

我尝试使用这篇文章作为例子,但是一旦我连线,我的路线似乎都没有工作(IIS Express返回401 /无法找到?)
Injecting dependencies into ASP.NET MVC 3 action filters. What's wrong with this approach?

如果有人有任何想法或建议,我会很感激! (现在它正在推动我的墙!)

谢谢!

2 个答案:

答案 0 :(得分:2)

Ninject的MVC扩展有一种机制,用于将依赖项注入过滤器,described in the documentation here

答案 1 :(得分:-3)

你可以试试这个

过滤

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    private IOutletService _outletService;
    private IModuleService _moduleService;

    public string Action { get; set; }
    public int Level { get; set; }

    public MarcusAuthorizeAttribute()
    {
       _outletService = DependencyResolver.Current.GetService<IHelloService>();
       _moduleService  = DependencyResolver.Current.GetService<IModuleService>();
    }
}

确保使用您正在使用的依赖项解析程序注册您的服务。