Injecting a dependency into a custom ModelBinder

做~自己de王妃 提交于 2020-01-14 13:44:08

问题


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, i.e. 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.


回答1:


I think you're going to have to make a service locator call either in the model binder, or to build up the model binder, or both.

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



回答2:


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.




回答3:


Inside your modelbinder you can call something like that

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


来源:https://stackoverflow.com/questions/579598/injecting-a-dependency-into-a-custom-modelbinder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!