O.O*_*.O. 2 ninject asp.net-mvc-3
这是一个MVC应用程序,其中控制器需要构造函数中的a DataContextCreator和a 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>();
}
}
Run Code Online (Sandbox Code Playgroud)
导航到页面时出现以下错误,即触发Controller的创建:
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
Run Code Online (Sandbox Code Playgroud)
以上所有内容都是在Win 7上使用MVC3 .Net 4.感谢您的帮助.
你为什么要写一个自定义控制器工厂?在使用Ninject.MVC3NuGet包时,这种情况并不常见.更常见的技术是使用在安装此NuGet时自动为您注册的自定义依赖项提供程序.
所以这里是步骤:
Ninject.MVC3NuGet包.在~/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"]);
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
2717 次 |
| 最近记录: |