How do I use custom model binder that supports dependency injection in ASP.NET Core?

人盡茶涼 提交于 2020-01-03 13:39:15

问题


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);
    }
}

回答1:


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.




回答2:


For ASP.NET Core 2.2, this should work for 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;
    }
}



回答3:


Instead of using a service locator pattern where the required service is retrieved in the model binder you can use IConfigureOptions to configure options with dependency injection. This allows you to delay the configuration of options until the dependency injection container has been built.

Here is a model binder having a dependency on 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.
    }
}

You need a provider for this model binder:

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);
    }
}

Normally, you would add the model binder provider in Startup using code like this:

services.AddMvc().AddMvcOptions(options =>
{
    options.ModelBinderProviders.Add(new CustomModelBinderProvider(customService));
});

However, as you have noted this is not possible. You cannot resolve customService while the system is being configured. The general solution to this problem is to use IConfigureOptions with the above code to configure the options but with the added benefit of being able to use dependency injection:

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));
}

This class has to be added to the container in Startup

services.AddSingleton<IConfigureOptions<MvcOptions>, CustomModelBinderConfigureMvcOptions>();

You are now able to use a model binder with a dependency.



来源:https://stackoverflow.com/questions/35640858/how-do-i-use-custom-model-binder-that-supports-dependency-injection-in-asp-net-c

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