O.O.
O.O.

Reputation: 2013

Passing parameters to the Controller Constructor using Ninject

This is an MVC application where the controllers need a DataContextCreator and a CustomerID in the constructor. My ControllerFactory looks like:

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>();
        }
    }

I get the following error when navigating to the Page i.e. triggering the creation of the 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

All of the above is using MVC3 .Net 4 on Win 7. Thanks for your help.

Upvotes: 2

Views: 3014

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

why did you write a custom controller factory? This is not common when working with the Ninject.MVC3 NuGet package. A more common technique is to use the custom dependency provider that is automatically registered for you when you install this NuGet.

So here are the steps:

  1. Get rid of your custom controller factory
  2. Install the Ninject.MVC3 NuGet package.
  3. Inside the ~/App_Start/NinjectWebCommon.cs file configure your kernel

    private static void RegisterServices(IKernel kernel)
    {
        kernel
            .Bind<IDataContextCreator>()
            .To<DefaultDataContextCreator>();
        kernel
            .Bind<MyController>()
            .ToSelf()
            .WithConstructorArgument("customerID", ctx => HttpContext.Current.Session["CustomerID"]);
    }        
    

Upvotes: 5

Related Questions