简体   繁体   中英

Injecting a dependency into a custom ModelBinder

I have an ASP.net MVC project in the works at the moment, and I'm wondering if the following could be possible: I have a custom ModelBinder class that has a reference to a service (essentially a fetcher) as a dependency. I want the dependency to be injected using an IoC container (currently Ninject) but there seems to be nowhere in the method chain that I can plug in something that says load the model binder from my IoC container.

My first thought is to have a generic object binder that then tries to retrieve a specific ModelBinder from the container, returning null if not found, and then stetting this up as a binder, ie something like: ModelBinders.Binders.Add(typeof(object),typeof(NinjectModelBinder));

but I'm unsure

  • a) if this will work
  • b) if it's really the right thing to do

I could forgo the resolving of the complex object until the Action method but it would be cleaner and more desirable to be able to provide the complex object (which is essentially loaded and built from the data access layer) as a parameter to the action.

Any thoughts/help appreciated.

我认为你将不得不在模型绑定器中进行服务定位器调用,或者建立模型绑定器,或者两者兼而有之。

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

I personally use setter injection in my scenario similar to yours. After looking it up, NInject calls this property injection. It works and gets the job done.

在你的模型绑定器中,你可以调用类似的东西

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM