1

I would like to use NInject.MVC3 to resolve which concrete class to instantiate when calling an Action method on a controller. So for example:

    [HttpPost]
    public ActionResult Index(IMyModelInterface model)
    {
        // do something

        return View();
    }

Obviously without dependency injection, MVC3 could not instantiate the IMyModelInterface, but I could bind that interface to a concrete class that implements this interface.

I have tried this and just get the error from the MVC framework trying to instantiate the interface.

So, first of all, is this a bad thing to attempt to do?

If it is not a stupid thing to do, how do I do it?

If it is a bad thing to do, how else should I do this. I have considered using a ViewModel then copying the parameters across? I am slightly reluctant to do this, as my model contains all the nice validation attributes for the view to use - and would have to duplicate this in the ViewModel, which seems to add maintenance overhead.

I have seen the SO question with doing this using Autofac.

I am using the most recent versions of NInject and NInject.MVC3 from the Nuget package.

Community
  • 1
  • 1
iandotkelly
  • 9,024
  • 8
  • 48
  • 67
  • Out of curiosity, why do you need it injected to the Action method? Why can't you use constructor injection on the controller? – BFree Nov 17 '11 at 17:14
  • I could use constructor injection if I was injecting dependency on some service, but I am trying to use DI on the model, so I can switch from one implementation of the model to another. I am now slightly regretting that choice now. – iandotkelly Nov 17 '11 at 17:20

2 Answers2

4

You could probably implement your own model binder to do this.

Subclass DefaultModelBinder, override CreateModel and use Ninject in this method return the appropriate type.

StanK
  • 4,750
  • 2
  • 22
  • 46
  • Thanks StanK - when I get more confident with the default patterns that NInject encourages, I might try that approach. – iandotkelly Nov 18 '11 at 13:54
3

Ninject does not allow you to inject dependencies in methods like that, as you can read here.
You should inject your dependencies through controller's constructor, properties or setter methods.

Community
  • 1
  • 1
Nelson Reis
  • 4,780
  • 9
  • 43
  • 61
  • Oh well, I will either wrap my model interface in another class to achieve this behavior, or I will rearrange my architecture to allow constructor injection on the controller - thanks. – iandotkelly Nov 17 '11 at 18:23
  • @Nelson, could you look at this very similar question: http://stackoverflow.com/questions/29971605/custom-authorizeattribute-ninject-property-injection-doesnt-work-injected-prop – Lyubomir Velchev Apr 30 '15 at 15:24