Enabling Dependency in a Custom ModelBinder

I currently have an ASP.net MVC project, and I wonder if the following is possible: I have my own ModelBinder class that refers to a service (essentially a choice) as a dependency. I want the dependency to be injected using the IoC container (currently Ninject), but it seems that nowhere in the method chain can I connect something that says loading the model link from my IoC container.

My first thought is to have a universal object binding, which then tries to retrieve a specific ModelBinder from the container, returning null if not found, and then stetting it as a binder, i.e. something like: ModelBinders.Binders.Add (TypeOf (object), TypeOf (NinjectModelBinder));

but Im unsure

  • a) if it will work
  • b) if this is really what needs to be done

I could refuse to resolve a complex object before an Action, but it would be cleaner and more desirable to be able to provide a complex object (which is essentially loaded and built at the data access level) as a parameter for the action.

Any thoughts / help appreciated.

+4
source share
3 answers

I think you will need to make a service locator call either in the model binding, or create a model connecting device, or both.

ModelBinders.Binders.Add(typeof(Customer), Resolve<CustomerBinder>()); 
+3
source

I personally use setter injection in my scenario like yours. After searching, NInject calls this injection of properties. He works and does his job.

+1
source

Inside your model block, you can call something like this

 IMyFetcher db = DependencyResolver.Current.GetService<IMyFetcher>(); 
0
source

All Articles