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

时间:2011-06-15 20:37:31

标签: asp.net-mvc asp.net-mvc-3 ninject ninject-2

我正在使用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>();
    }

}

修改

我升级到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
    {
}

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

2 个答案:

答案 0 :(得分:12)

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

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

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

    public interface IFoo { }
    public class Foo : IFoo { }
    
    public class MyFooFilter : AuthorizeAttribute
    {
        public MyFooFilter(IFoo foo)
        {
    
        }
    }
    

    然后配置内核:

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

    public interface IFoo { }
    public class Foo : IFoo { }
    
    public class MyFooFilter : AuthorizeAttribute
    {
        [Inject]
        public IFoo Foo { get; set; }
    }
    

    然后配置内核:

    kernel.Bind<IFoo>().To<Foo>();
    

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

    [MyFooFilter]
    public ActionResult Index()
    {
        return View();
    }
    

答案 1 :(得分:0)

相关问题