我在stackoverflow上找到了很多关于如何在ASP.NET MVC3中使用Ninject进行ActionFilter属性注入的不确定文章和问题。
有人能给我一个清晰的例子吗?
这是我的自定义认证属性。
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
[Inject]
public IService Service { get; set; }
[Inject]
public IAuthenticationHelper AuthenticationHelper { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
//My custom code
}
}
我正在使用WebActivator来设置Ninject
[assembly: WebActivator.PreApplicationStartMethod(typeof(MyProject.Web.AppStart_NinjectMvc3), "Start")]
namespace MyProject.Web {
public static class AppStart_NinjectMvc3 {
public static void RegisterServices(IKernel kernel) {
//Binding things
}
public static void Start() {
// Create Ninject DI Kernel
IKernel kernel = new StandardKernel();
// Register services with our Ninject DI Container
RegisterServices(kernel);
// Tell ASP.NET MVC 3 to use our Ninject DI Container
DependencyResolver.SetResolver(new NinjectServiceLocator(kernel));
}
}
}
我的服务和辅助类从未被注入。我需要改变什么?
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
- 这行代码不是必需的。NinjectHTTPApplication 在Application_Start
中注册了DependencyResolver
。 - LukLed