“ Microsoft.Extensions.Hosting”中用于控制台应用程序的通用主机生成器的Web主机生成器的等效代码是什么:
var hostBuilder = WebHost.CreateDefaultBuilder(args).UseConfiguration(config).UseStartup<TStartup>();
答案 0 :(得分:0)
我找不到完全类似的东西。我使用下一个代码。为我的后台服务。
public static async Task Main(string[] args)
{
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost => configHost.AddEnvironmentVariables("ASPNETCORE_"))
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(GetConfigDirectoryPath());
configApp.AddJsonFile("appsettings.json", optional: false);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);
})
.ConfigureServices(ConfigureServices)
.UseHostedService<MyBackgroundService>()
.Build();
await host.RunAsync();
}
private static void ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(hostBuilderContext.Configuration.GetConnectionString("Default")));
services.AddTransient<IDbContextProvider<AppDbContext>, DefaultDbContextProvider>();
services.AddTransient<IUnitOfWorkManager, UnitOfWorkManager>();
services.AddTransient(typeof(IUnitOfWork), typeof(EfCoreUnitOfWork));
services.AddTransient(typeof(IReadOnlyRepository<>), typeof(EfCoreReadOnlyRepositoryBase<>));
services.AddTransient(typeof(IReadOnlyRepository<,>), typeof(EfCoreReadOnlyRepositoryBase<,>));
services.AddTransient(typeof(IRepository<>), typeof(EfCoreRepositoryBase<>));
services.AddTransient(typeof(IRepository<,>), typeof(EfCoreRepositoryBase<,>));
services.AddDistributedRedisCache(options => options.Configuration = hostBuilderContext.Configuration.GetSection("Redis:Configuration").Value);
//Register AutoMapper profiles
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
services.AddAutoMapper(assemblies);
}
正在实施后台服务
public class MyBackgroundService : BackgroundService
public static class Extensions
{
public static IHostBuilder UseHostedService<T>(this IHostBuilder hostBuilder)
where T : class, IHostedService, IDisposable
{
return hostBuilder.ConfigureServices(services =>
services.AddHostedService<T>());
}
}