使用Ninject将参数传递给Controller Constructor

时间:2012-10-15 20:51:32

标签: asp.net-mvc-3 ninject

这是一个MVC应用程序,其中控制器在构造函数中需要DataContextCreatorCustomerID。我的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.感谢您的帮助。

1 个答案:

答案 0 :(得分:6)

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

以下是步骤:

  1. 摆脱自定义控制器工厂
  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"]);
    }        
    
相关问题