这是一个MVC应用程序,其中控制器需要在构造函数中DataContextCreator
和CustomerID
。我的ControllerFactory
如下所示:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
return null;
}
else
{
string customerID = requestContext.HttpContext.Session["CustomerID"].ToString();
return (IController)ninjectKernel.Get(controllerType, new IParameter[]{new Parameter("CustomerID", customerID, true)});
}
}
private void AddBindings()
{
ninjectKernel.Bind<IDataContextCreator>().To<DefaultDataContextCreator>();
}
}
导航到页面时出现以下错误,即触发控制器的创建:
Ninject.ActivationException: Error activating int
No matching bindings are available, and the type is not self-bindable.
Activation path:
2) Injection of dependency int into parameter CustomerID of constructor of type MyController
1) Request for MyController
以上所有内容都在Win 7上使用MVC3 .Net 4。感谢您的帮助。
为什么要编写自定义控制器工厂?使用Ninject.MVC3
NuGet 包时,这并不常见。更常见的技术是使用在安装此 NuGet 时自动注册的自定义依赖项提供程序。
所以这里是步骤:
- 摆脱您的自定义控制器工厂
- 安装
Ninject.MVC3
NuGet 包。 -
在
~/App_Start/NinjectWebCommon.cs
文件中配置内核private static void RegisterServices(IKernel kernel) { kernel .Bind<IDataContextCreator>() .To<DefaultDataContextCreator>(); kernel .Bind<MyController>() .ToSelf() .WithConstructorArgument("customerID", ctx => HttpContext.Current.Session["CustomerID"]); }