首先,我是新手Ninject
。
我正在尝试绑定到 MVC4 中的动作过滤器。
我在 SO 中发现了很多问题,但它们都是关于 MVC3-2 的,而且大多数都是几年前的问题 - MVC3、过滤器配置、Ninject 和 MVC3
以下是我的测试代码 -
public class MyAuthorizeAttribute : AuthorizeAttribute
{
[Inject]
public IProductRepository _productRepository { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
var products = _productRepository.Products; // this is null
base.OnAuthorization(filterContext);
}
}
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel _kernal;
public NinjectControllerFactory()
{
_kernal = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(
System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null :
(IController)_kernal.Get(controllerType);
}
private void AddBindings()
{
// This is working in ProductController
_kernal.Bind<IProductRepository>().To<EFProductRepository>();
// I'm trying to make this work!
_kernal.BindFilter<IProductRepository>().To<EFProductRepository>();
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ControllerBuilder.Current.SetControllerFactory(
new NinjectControllerFactory());
}
}
我尝试添加using Ninject.Web.Mvc.FilterBindingSyntax;
以获取BindFilter
.
Ninject MVC4
但是,我找不到NuGet
我应该使用 Ninject.MVC3 吗?
任何建议将不胜感激!