问题描述
我想使用MVC自定义模型粘结剂,我想从我的IoC容器解决。我遇到的问题是,我无法访问我的容器,而我加入MVC服务,因为我的容器尚未建成(我需要建立我的容器之前添加MVC)。感觉像鸡/鸡蛋的问题,我相信我缺少一个简单的解决方案。
例如:
services.AddMvc()AddMvcOptions(选项=>
{
options.ModelBinders.Add(serviceProvider.Resolve&所述; CustomModelBinder>());
});
我的自定义模型粘合剂是这样的:
公共类CustomModelBinder:IModelBinder
{
私人的IServiceProvider的ServiceProvider; 公共CustomModelBinder(的IServiceProvider的ServiceProvider)
{
this.serviceProvider =的ServiceProvider;
} 公共任务< ModelBindingResult> BindModelAsync(ModelBindingContext的BindingContext)
{
VAR模型= serviceProvider.GetService(bindingContext.ModelType);
bindingContext.Model =模型; VAR粘结剂=新GenericModelBinder();
返回binder.BindModelAsync(BindingContext中);
}
}
每这里的帖子:
要直接回答你的问题,使用:
bindingContext.OperationBindingContext.ActionContext.HttpContext.RequestServices
在一个侧面说明,你也可以选择使用的选项 [FromServices]
来解决它。
I am trying to use a custom model binder in MVC that I want resolved from my IoC container. The issue I am having is that I can't access my container while I am adding the MVC service, because my container isn't built yet (and I need to add MVC before building my container). Feels like a chicken/egg issue, and I am sure I am missing a simple solution.
Example:
services.AddMvc().AddMvcOptions(options =>
{
options.ModelBinders.Add(serviceProvider.Resolve<CustomModelBinder>());
});
My custom model binder looks like this:
public class CustomModelBinder : IModelBinder
{
private IServiceProvider serviceProvider;
public CustomModelBinder(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
{
var model = serviceProvider.GetService(bindingContext.ModelType);
bindingContext.Model = model;
var binder = new GenericModelBinder();
return binder.BindModelAsync(bindingContext);
}
}
Per the post here: https://github.com/aspnet/Mvc/issues/4167
To answer your question directly, use:
bindingContext.OperationBindingContext.ActionContext.HttpContext.RequestServices
On a side note, you also have the option of using [FromServices]
to resolve it for you.
这篇关于我如何使用支持MVC6依赖注入自定义模型粘合剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!