Search code examples
c#asp.net-mvcmodel-binding.net-core-3.1custom-model-binder

Not getting my service injected in Model Binder Provider


Is there any reason why I'm not getting an injected service into my custom RegisterBinderProvider?

            services.AddScoped<IPasswordHasher, PasswordHasher>();

            services.AddMvc(options =>
            {
                RegisterBinderProvider registerBinderProvider = 
                     DependencyResolver.Current.GetService<RegisterBinderProvider>();
                options.ModelBinderProviders.Insert(0, registerBinderProvider);
                options.Filters.Add(typeof(ApiExceptionFilter));
            });

After this code, when I'm in the RegisterBinderProvider class, I see the value of the PasswordHasher service is null. However, I checked the services already injected before inserting the RegisterBinderProvider, and I could find the PasswordHasher in it.

In case you need it, this is my custom BinderProvider:

    public class RegisterBinderProvider : IModelBinderProvider
    {
        private readonly IPasswordHasher _passwordHasher;

        public RegisterBinderProvider(IPasswordHasher passwordHasher)
        {
            _passwordHasher = passwordHasher;
        }

        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context.Metadata.ModelType == typeof(User))
            {
                return new RegisterBinder(_passwordHasher);
            }

            return null;
        }
    }

I hope I've provided enough information to understand my problem, thank you!


Solution

  • You could reslove the service in the GetBinder method using the context parameter:

    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
            var service = context.Services.GetRequiredService<IPasswordHasher>();
            if (context.Metadata.ModelType == typeof(User))
            ...
    }
    

    Since you're only creating a single instance of your RegisterBinderProvider and call the AddMvc and ModelBinderProviders.Insert methods once, it doesn't make much sense to trying to resolve a scoped service at startup.