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.

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top