简体   繁体   English

将依赖项注入自定义ModelBinder

[英]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. 我现在正在开发一个ASP.net MVC项目,我想知道以下是否可行:我有一个自定义的ModelBinder类,它引用了一个服务(本质上是一个fetcher)作为依赖项。 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. 我希望使用IoC容器(当前为Ninject)注入依赖项,但在方法链中似乎没有任何地方可以插入一些内容,即从IoC容器中加载模型绑定器。

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)); 我的第一个想法是有一个通用的对象绑定器,然后尝试从容器中检索特定的ModelBinder,如果没有找到则返回null,然后将其作为绑定器,例如:ModelBinders.Binders.Add(typeof(object) )的typeof(NinjectModelBinder));

but I'm unsure 但我不确定

  • a) if this will work a)如果这样可行
  • b) if it's really the right thing to do b)如果它真的是正确的事情

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. 我可以放弃复杂对象的解析直到Action方法,但是能够提供复杂对象(基本上是从数据访问层加载和构建)作为操作的参数会更清晰,更可取。

Any thoughts/help appreciated. 任何想法/帮助表示赞赏。

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

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

I personally use setter injection in my scenario similar to yours. 我个人在我的场景中使用setter注入类似于你的。 After looking it up, NInject calls this property injection. 在查找之后,NInject调用此属性注入。 It works and gets the job done. 它起作用并完成工作。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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