views:

1433

answers:

4

I want to use dependency injection in an medium trust environment. To that aim I picked Ninject as Iv been told its light weight. How do I set-up injection into the controllers?

When I tried to create a custom controller factory:

 public class NinjectControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel _kernel;
        public NinjectControllerFactory(params IModule[] modules)
        {
            _kernel = new StandardKernel(modules);
        }

        public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            IController controller = base.CreateController(requestContext, controllerName);
            _kernel.Inject(controller);
            return controller;
        }
    }

But I'm encountering this error:

 System.InvalidOperationException was unhandled by user code
  Message="An error occurred while creating a controller of type 'xxx'.

If the controller doesn't have a controller factory, ensure that it has a parameterless public constructor."

Any idea how to get Ninject or any other IoC framework working under medium trust (meaning no use of reflection)

+1  A: 

Try to set this option when creating your container:

UseReflectionBasedInjection = true;
Koistya Navin
A: 

Good tip(but did you mean set it to false?), I changed my constructor so that its like this:

public NinjectControllerFactory(params IModule[] modules)
        {
            _kernel = new StandardKernel(modules);
            _kernel.Options.UseReflectionBasedInjection = false;
        }

This gets the same exception though.

I also tried overriding GetControllerInstance like this too

  protected override IController GetControllerInstance(Type controllerType)
    {
        return _kernel.Get(controllerType) as IController;
    }

But this throws an security exception because it uses reflection.

Dan
+2  A: 

To run Ninject 1.x in medium trust, you must set the UseReflectionBasedInjection option to true. Ninject 2.0 does not suffer from this limitation.

Reflection is actually not a protected operation in medium trust, but lightweight code generation (which Ninject uses by default for injection) is -- at least before .NET 3.5 SP1.

Once you switch to reflection-based injection, your code should work as intended. I'd also encourage you to look at Ninject.Framework.Mvc (for Ninject 1.x) or Ninject.Web.Mvc (for Ninject 2.0). These extensions handle the heavy-lifting for you.

Nate Kohari
I was using ninject 2. Ninject.Web.Mvc is not medium trust firendly
Dan
+1  A: 

I never managed to resolved this issue in the end, I switched to Unity - works in medium trust without any hassle.

Dan