(MVC 6) How to get an instance of IServiceProvider after a class is instantiated.

129 views
Skip to first unread message

Sergey Sagan

unread,
Feb 25, 2016, 10:31:10 PM2/25/16
to Autofac
Unfortunately, as of right now, MVC requires that it be added as a service in ConfigureServices before Autofac is Built() that means for a Custom Model Binder that needs IServiceProvider can't get it injected in the constructor.

We add our model binder like this:

            services.AddMvc().AddMvcOptions(options =>
            {
                options.ModelBinders.Clear();
                options.ModelBinders.Add(new IoCModelBinder());

            });

and the binder itself looks like this:

    public class IoCModelBinder : IModelBinder
    {
        internal static IServiceProvider ServiceProvider { get; set; }

        public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            var model = ServiceProvider.GetService(bindingContext.ModelType);
            bindingContext.Model = model;

            var binder = new GenericModelBinder();
            return binder.BindModelAsync(bindingContext);
        }
    }

At this point, we have to manually set the ServiceProvider  property from ConfigureServices after the DI is built! I know, super hacky. We'd like to somehow resolve it inside our BindModelAsync method. Basically make it look like this:

    public class IoCModelBinder : IModelBinder
    {
        private IServiceProvider serviceProvider;

        public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            if (serviceProvider == null)
                serviceProvider = RESOLVETHISTHING<IServiceProvider >();

            var model = serviceProvider .GetService(bindingContext.ModelType);
            bindingContext.Model = model;

            var binder = new GenericModelBinder();
            return binder.BindModelAsync(bindingContext);
        }
    }

How do we do it?

Travis Illig

unread,
Feb 26, 2016, 11:43:33 AM2/26/16
to Autofac
I'm not sure if you've asked them, but since Autofac (and other IoC containers) are now all abstracted out by Microsoft.Extensions.DependencyInjection, this might be a good question for the MVC team. The answer will be the same for every IoC integration.
Reply all
Reply to author
Forward
0 new messages