我试图在MVC中使用我希望从我的IoC容器中解析的自定义模型绑定器。我遇到的问题是我在添加MVC服务时无法访问我的容器,因为我的容器尚未构建(我需要在构建容器之前添加MVC)。感觉像鸡/蛋问题,我相信我错过了一个简单的解决方案。
例:
services.AddMvc().AddMvcOptions(options =>
{
options.ModelBinders.Add(serviceProvider.Resolve<CustomModelBinder>());
});
我的自定义模型绑定器如下所示:
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);
}
}
根据这里的帖子:https://github.com/aspnet/Mvc/issues/4167
要直接回答您的问题,请使用:
bindingContext.OperationBindingContext.ActionContext.HttpContext.RequestServices
另外,您还可以选择使用[FromServices]
为您解决此问题。
对于ASP.NET Core 2.2,这适用于DI:
public class CustomModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
// dependency injection
var model = bindingContext.HttpContext.RequestServices.GetService(bindingContext.ModelType);
// other changes...
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}
您可以使用IConfigureOptions
配置依赖注入的选项,而不是使用在模型绑定器中检索所需服务的服务定位器模式。这允许您延迟选项的配置,直到构建依赖项注入容器。
这是一个依赖于ICustomService
的模型绑定器:
class CustomModelBinder : IModelBinder
{
private readonly ICustomService customService;
public CustomModelBinder(ICustomService customService) => this.customService = customService;
public Task BindModelAsync(ModelBindingContext bindingContext)
{
// Use customService during model binding.
}
}
您需要此模型绑定器的提供程序:
class CustomModelBinderProvider : IModelBinderProvider
{
private readonly ICustomService customService;
public CustomModelBinderProvider(ICustomService customService) => this.customService = customService;
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
// Return CustomModelBinder or null depending on context.
return new CustomModelBinder(customService);
}
}
通常,您可以使用以下代码在Startup
中添加模型绑定程序提供程序:
services.AddMvc().AddMvcOptions(options =>
{
options.ModelBinderProviders.Add(new CustomModelBinderProvider(customService));
});
但是,正如您所指出的那样,这是不可能的。在配置系统时,无法解析customService
。这个问题的一般解决方案是使用带有上述代码的IConfigureOptions
来配置选项,但是还具有能够使用依赖注入的额外好处:
class CustomModelBinderConfigureMvcOptions : IConfigureOptions<MvcOptions>
{
private readonly ICustomService customService;
public CustomModelBinderConfigureMvcOptions(ICustomService customService) => this.customService = customService;
public void Configure(MvcOptions options)
=> options.ModelBinderProviders.Add(new CustomModelBinderProvider(customService));
}
必须将此类添加到Startup
中的容器中
services.AddSingleton<IConfigureOptions<MvcOptions>, CustomModelBinderConfigureMvcOptions>();
您现在可以使用具有依赖关系的模型绑定器。