Search code examples
c#asp.net-coredependency-injectionautofacmodel-binding

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


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

Solution

  • 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.