Calling 'BuildServiceProvider' from application code results in copy of Singleton warning in .Net Core
Each Service provider will have its own cache of singleton instances. If multiple service builders are created in code, it will cause the singleton instances to be created more than once, which contradicts the singleton property which is only once the instance is present throughout the lifetime of the application.
Please find the alternative solution below, when you want to get the registered services for dependency injection.
First, create a static class with a one property IServiceProvider type
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ILoggerEntry, LoggerEntry>();
services.AddTransient<IMongoRepository, MongoRepository>();
}
Second, configure your services in ConfigureServices() method in Startup.cs and define the lifetime of the service instance using either Transient, Scoped or Singleton types.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ILoggerEntry, LoggerEntry>();
services.AddTransient<IMongoRepository, MongoRepository>();
}
Third, set the Static class provider property in Startup.Configure() method. ApplicationServices are used in situations where you need to get an instance of dependency service during the configuration phase. ApplicationServices are for the lifetime of the app.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
StaticServiceProvider.Provider = app.ApplicationServices;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
That's it. You can now call GetService method almost anywhere in your application and get the service instance that you require using the GetService() method.
public static class StaticClass
{
private static IServiceProvider ServiceProvider
= StaticServiceProvider.Provider;
private static ILoggerEntry loggerEntry = (ILoggerEntry)ServiceProvider?.GetService(typeof(ILoggerEntry));
private static IMongoRepository mongoRepository
= (IMongoRepository)ServiceProvider?.GetService(typeof(IMongoRepository));
public static string GetSubString(this string str)
{
loggerEntry.AddToLog("Inside Extension Method");
return str.Substring(3);
}
}
Comments
Post a Comment