我使用的是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 { }
它告诉我它想要一个没有参数的构造函数.所以我一定错过了什么.
解决方法
过滤器的问题在于它们是属性.如果你定义一个需要某种依赖关系的属性的构造函数,你就永远无法将它应用于任何方法:因为所有传递给属性的值必须在编译时才知道.
所以基本上你有两种可能性:
>使用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 ) );
>使用属性注入:
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(); }