我正在使用 asp.net mvc 3、ninject 2.0 和 ninject mvc 3 插件。
我想知道如何将服务层放入我的过滤器中(在本例中是授权过滤器?)。
我喜欢进行构造函数注入,所以这是可能的还是我必须进行属性注入?
Thanks
Edit
我有这个用于属性注入,但我的属性始终为空
[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>();
}
}
Edit
我升级到 ninject 2.2 并终于开始工作了。
Edit 2
我将尝试为我的授权过滤器执行构造函数,但我不确定如何传递角色。我猜我必须通过 ninject 来做到这一点?
Edit 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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)