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

3

10

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);
    }
}
Pantaloon answered 26/2, 2016 at 0:2 Comment(0)
G
11

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.

Gyneco answered 26/2, 2016 at 20:5 Comment(0)
D
3

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;
    }
}
Dunton answered 26/3, 2019 at 23:4 Comment(0)
F
2

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.

Fredrika answered 25/7, 2019 at 8:28 Comment(1)
I am getting error on CreateHostBuilder(args).Build().Run(), Unable to resolve service for type 'IMyinterface' while attempting to activate 'CustomModelBinderConfigureMvcOptions'.Snooty

© 2022 - 2024 — McMap. All rights reserved.