gpt4 book ai didi

asp.net-mvc-3 - 使用 Ninject 将参数传递给 Controller Constructor

转载 作者:行者123 更新时间:2023-12-02 08:45:22 32 4
gpt4 key购买 nike

这是一个 MVC 应用程序,其中 Controller 在构造函数中需要一个 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>();
}
}

导航到页面时出现以下错误,即触发 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

以上所有内容均在 Win 7 上使用 MVC3 .Net 4。感谢您的帮助。

最佳答案

你为什么要写一个自定义 Controller 工厂?这在使用 Ninject.MVC3 NuGet 包时并不常见。一种更常见的技术是使用在您安装此 NuGet 时自动为您注册的自定义依赖项提供程序。

步骤如下:

  1. 摆脱您的自定义 Controller 工厂
  2. 安装 Ninject.MVC3 NuGet 包。
  3. ~/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"]);
    }

关于asp.net-mvc-3 - 使用 Ninject 将参数传递给 Controller Constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903785/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com