Last active
April 11, 2019 15:01
-
-
Save cbdabner/def1af01e3be2ba7752320c7663d6ff7 to your computer and use it in GitHub Desktop.
IStartupTask outside WebhostBuilder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DbMigrationTask<TDbContext> : IStartupTask | |
where TDbContext : DbContext | |
{ | |
private readonly TDbContext _dbContext; | |
public DbMigrationTask(TDbContext dbContext) | |
{ | |
_dbContext = dbContext; | |
} | |
public async Task ExecuteAsync(CancellationToken cancellationToken = default) | |
{ | |
await _dbContext.Database.MigrateAsync(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ServiceCollectionExtensions | |
{ | |
public static IServiceCollection AddStartupTask<TStartupTask>(this IServiceCollection services) | |
where TStartupTask : class, IStartupTask => | |
services | |
.AddTransient<TStartupTask>() | |
.AddTransient<IStartupTask, ScopedStartupTask<TStartupTask>>(); | |
private class ScopedStartupTask<TStartupTask> : IStartupTask | |
where TStartupTask : class, IStartupTask | |
{ | |
private readonly IServiceProvider _services; | |
public ScopedStartupTask(IServiceScope scope) | |
{ | |
_services = scope.ServiceProvider; | |
} | |
public Task ExecuteAsync(CancellationToken cancellationToken = default) | |
=> _services.GetRequiredService<TStartupTask>().ExecuteAsync(cancellationToken); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class WebHostExtensions | |
{ | |
public static async Task RunWithTasksAsync(this IWebHost webHost, CancellationToken cancellationToken = default) | |
{ | |
foreach (var task in webHost.Services.GetServices<IStartupTask>()) | |
{ | |
await task.ExecuteAsync(cancellationToken); | |
} | |
await webHost.RunAsync(cancellationToken); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment