I have the following code in my Startup
class, which uses a custom instance of IModelBinderProvider
. Most input formatters require a ILogger
instance, so I need to have an ILoggerFactory
, and for that I want to use the configured one, which logs to specified destinations at specified verbosity. I'm grabbing the ILoggerFactory
from a newly built IServiceProvider
:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvcCore(
options =>
{
...
var serviceProvider = services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
options.ModelBinderProviders.Clear();
options.ModelBinderProviders.Add(
new MyCustomBinderProvider(options.InputFormatters, loggerFactory)
);
...
}
);
...
}
The problem is that I'm getting the following warning:
Startup.cs(62, 43): [ASP0000] Calling 'BuildServiceProvider' from application code results in an
additional copy of singleton services being created. Consider alternatives such
as dependency injecting services as parameters to 'Configure'.
I took a look on this question: Resolving instances with ASP.NET Core DI from within ConfigureServices. However, my code is a lambda of AddMvcCore
, which is configuring the options
object. In other words, by the time the Configure
is called, the MVC options are already defined.
Is there a way of doing the right thing here, i.e. prevent an extraneous instance of IServiceProvider
?