Reputation: 37875
I have an aspnetcore app.
During startup, it does the usual startup actions.
After these are complete, I need to do some verification to ensure it was set up correctly. In particular, I need to call a stored procedure in the database using the default connection string. In other words, I need to create a class that uses dependency injection so that needs to be complete before it is called.
Just not sure where to put such code in StartUp.
Upvotes: 40
Views: 35737
Reputation: 11090
Since .net core 2.0, you should probably implement your own IHostedService
. Each registered IHostedService
will be started in the order they were registered. If they fail, they can cause the host to fail to start.
Since you wish to perform database operations, you should also create a new service scope to control the lifetime of your database connection.
public class StartupService : IHostedService{
private IServiceProvider services;
public StartupService(IServiceProvider services){
this.services = services;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
using var scope = serviceProvider.CreateScope();
using var context = scope.ServiceProvider.GetRequiredService<...>();
... do work here
}
}
// then in configure services
services.AddHostedService<StartupService>();
Note that EF Core 5 introduces IDbContextFactory
, which could be used to create a context outside of any DI service scope.
Each of the other answers to this question will run while the web server is being configured, which is also executed within an IHostedService
.
Upvotes: 16
Reputation: 2805
Or use IStartupFilter
.
This is mainly for configuring middleware, but should allow you to perform actions after the configuration is over.
Upvotes: 8
Reputation: 10459
Probably the best place is in Configure
method after UseMvc()
call. That is also the place where you usually apply migrations. You can add as many classes that DI knows as parameter.
For example:
public void Configure(IApplicationBuilder app)
or
public void Configure(IApplicationBuilder app, AppUserManager userManager, IServiceProvider serviceProvider)
or
public void Configure(IApplicationBuilder app, MyDbContext context)
If you want to check this in background (only if you don't care about result - application should run also if verification fails), check my answer here.
Also this answer may help you.
Upvotes: 35