A basic ConfigureServices method looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
//custom logic here
}
Right before the method ends I want to run some custom logic. However I need to access the ApplicationDbContext and get some configuration from there. Another thing is I want to use the AuthMessageSenver
service to send an email.
My question: how can I access a service I declared within the same method. Or how can I use my ApplicationdDbContext to get the data from database.
You can use BuildServiceProvider
method to resolve a service:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddTransient<IEmailSender, AuthMessageSender>();
//...
var provider = services.BuildServiceProvider();
var emailSender= provider.GetService<IEmailSender>();
// use emailSender
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With