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>();
}
For the next step to configure the Static class provider property there are two ways to do that.
- 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();
});
}
- (OR) You can also call the BuildServiceProvider() method which creates a ServiceProvider containing services from the provided IServiceCollection.
public static class GetServicesExtension
{
public static IServiceCollection GetServices(this IServiceCollection services)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
StaticServiceProvider.Provider
= services.BuildServiceProvider();
return services;
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ILoggerEntry, LoggerEntry>();
services.AddTransient<IMongoRepository, MongoRepository>();
services.GetServices();
}
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