首先,我是Ninject
的新手。
我正在尝试绑定到MVC4中的Action Filter。
我在SO中发现了很多问题,但所有问题都与MVC3-2有关,其中大多数都是几年前的问题 - MVC3,Filter configurations,Ninject and 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
任何建议都将不胜感激!
答案 0 :(得分:0)
是的,使用Ninject.MVC3,它在MVC4中工作正常,因为nuget包将设置版本转发。但是,此版本不能直接与WebAPI一起使用,如果您打算将Ninject与WebAPI一起使用,则需要安装扩展包。