如何使用Ninject将服务注入授权过滤器?

cho*_*bo2 7 asp.net-mvc ninject ninject-2 asp.net-mvc-3

我使用的是asp.net mvc 3,ninject 2.0和ninject mvc 3插件.

我想知道如何将服务层添加到我的过滤器中(在这种情况下是授权过滤器?).

我喜欢做构造函数注入,所以这是可能的还是我必须注入属性?

谢谢

编辑

我有这个属性注入,但我的属性总是为空

  [Inject]
        public IAccountService AccountServiceHelper { get; set; }


        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // check if context is set
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            // check if user is authenticated
            if (httpContext.User.Identity.IsAuthenticated == true)
            {
                // stuff here
                return true;
            }

            return false;
        }



    /// <summary>
    /// Application_Start
    /// </summary>
    protected void Application_Start()
    {

        // Hook our DI stuff when application starts
        IKernel kernel = SetupDependencyInjection();

        RegisterMaps.Register();

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

    }


    public IKernel SetupDependencyInjection()
    {
        IKernel kernel = CreateKernel();
        // Tell ASP.NET MVC 3 to use our Ninject DI Container
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

        return kernel;
    }

    protected IKernel CreateKernel()
    {
        var modules = new INinjectModule[]
                          {
                             new NhibernateModule(),
                             new ServiceModule(),
                             new RepoModule()
                          };

        return new StandardKernel(modules);
    }


public class ServiceModule : NinjectModule
{
    public override void Load()
    {
        Bind<IAccountService>().To<AccountService>();
    }

}
Run Code Online (Sandbox Code Playgroud)

编辑

我升级到ninject 2.2并最终得到它的工作.

编辑2

我将尝试为我的授权过滤器执行构造方法,但我不确定如何传递角色.我猜我必须通过ninject做到这一点?

编辑3

这就是我到目前为止所拥有的

 public class MyAuthorizeAttribute : AuthorizeAttribute 
    {
        private readonly IAccountService accountService;

        public MyAuthorizeAttribute(IAccountService accountService)
        {
            this.accountService = accountService;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return base.AuthorizeCore(httpContext);
        }
    }

  this.BindFilter<MyAuthorizeAttribute>(FilterScope.Controller, 0)
                .WhenControllerHas<MyAuthorizeAttribute>();

  [MyAuthorize]
    public class MyController : BaseController
    {
}
Run Code Online (Sandbox Code Playgroud)

它告诉我它想要一个没有参数的构造函数.所以我一定错过了什么.

Dar*_*rov 13

过滤器的问题在于它们是属性.如果你定义一个需要某种依赖关系的属性的构造函数,你将永远无法将它应用于任何方法:因为所有传递给属性的值必须在编译时才知道.

所以基本上你有两种可能:

  1. 使用Ninject全局应用过滤器,而不是用它来装饰控制器/操作:

    public interface IFoo { }
    public class Foo : IFoo { }
    
    public class MyFooFilter : AuthorizeAttribute
    {
        public MyFooFilter(IFoo foo)
        {
    
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    然后配置内核:

    kernel.Bind<IFoo>().To<Foo>();
    kernel.BindFilter<MyFooFilter>(FilterScope.Action, 0).When(
        (controllerContext, actionDescriptor) => 
            string.Equals(
                controllerContext.RouteData.GetRequiredString("controller"),
                "home",
                StringComparison.OrdinalIgnoreCase
            )
    );
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用属性注入:

    public interface IFoo { }
    public class Foo : IFoo { }
    
    public class MyFooFilter : AuthorizeAttribute
    {
        [Inject]
        public IFoo Foo { get; set; }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    然后配置内核:

    kernel.Bind<IFoo>().To<Foo>();
    
    Run Code Online (Sandbox Code Playgroud)

    并使用自定义过滤器装饰一些控制器/操作:

    [MyFooFilter]
    public ActionResult Index()
    {
        return View();
    }
    
    Run Code Online (Sandbox Code Playgroud)