How to override the ASP.NET MVC 3 model middleware to resolve dependencies (using ninject) during model creation?

I have an ASP.NET MVC 3 application that uses Ninject to resolve dependencies. All I had to do so far was make the Global file inherit from NinjectHttpApplication , and then override the CreateKernel method to map the dependency bindings. After that, I can enable interface dependencies in my MVC controller constructs, and ninject can resolve them. All this is great. Now I would also like to resolve dependencies in model binding when it instantiates my model, but I don't know how to do it.

I have a view model:

 public class CustomViewModel { public CustomViewModel(IMyRepository myRepository) { this.MyRepository = myRepository; } public IMyRepository MyRepository { get; set; } public string SomeOtherProperty { get; set; } } 

Then I have an action method that takes a view model object:

 [HttpPost] public ActionResult MyAction(CustomViewModel customViewModel) { // Would like to have dependency resolved view model object here. } 

How to override the default middleware to enable ninject and resolve dependencies?

+6
source share
1 answer

The presence of viewing models depends on the repository - this is an anti-template. Do not do that.

If you still insist, here is an example of what the model binding would look like. The idea is to have a custom CreateModel where you override the CreateModel method:

 public class CustomViewModelBinder : DefaultModelBinder { private readonly IKernel _kernel; public CustomViewModelBinder(IKernel kernel) { _kernel = kernel; } protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { return _kernel.Get(modelType); } } 

which you could register for any viewing model, you need to have this injection:

 ModelBinders.Binders.Add(typeof(CustomViewModel), new CustomViewModelBinder(kernel)); 
+9
source

Source: https://habr.com/ru/post/891416/


All Articles