我最近在coreclr(x64)上使用1.0.0-rc1-update1创建了一个ASP.NET服务。因此,该服务能够在所有支持的操作系统上运行;很酷!我的服务只暴露了一个简单的“TODO”API并使用了Entity Framework 7.0 ORM。对于持久性,它在Linux上使用Sqlite DB,在Windows上使用SQL Server DB。
我想知道是否有基于约定的方法允许Startup.cs处理各种操作系统的不同服务配置?例如,我的EF配置不同,因为它在Linux上使用Sqlite,在Windows上使用SQL Server。
以下文章详细介绍了一些基于约定的配置方法,但似乎只允许不同的方法用于“开发”,“暂存”,“生产”环境的更高级别抽象: https://docs.asp.net/en/latest/fundamentals/environments.html
目前,我只是在Startup.cs的构造函数中注入IRuntimeEnviroment并保存它。然后,当调用ConfigureServices时,我检查IRuntimeEnvironment的OperatingSystem属性并相应地调整EF配置(我在下面提供的完整Startup.cs)...
非常感谢任何有关其他(或推荐)方法的指导。
public class Startup
{
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
public IConfigurationRoot Configuration { get; set; }
public IRuntimeEnvironment RuntimeEnv { get; set; }
public Startup(IHostingEnvironment env, IRuntimeEnvironment runtimeEnv)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
RuntimeEnv = runtimeEnv;
}
public void ConfigureServices(IServiceCollection services)
{
if (RuntimeEnv.OperatingSystem == "Windows")
{
var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<TodoContext>(options => options.UseSqlServer(connectionString));
}
else if (RuntimeEnv.OperatingSystem == "Linux")
{
var connectionString = Configuration["Data:DefaultConnection:SqlLiteConnection"];
var path = PlatformServices.Default.Application.ApplicationBasePath;
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<TodoContext>(options => options.UseSqlite("Filename=" + Path.Combine(path, "TodoApp.db")));
}
services
.AddMvcCore(options =>
{
options.OutputFormatters.Clear();
options.OutputFormatters.Add(new HttpNotAcceptableOutputFormatter());
options.OutputFormatters.Add(new HttpNoContentOutputFormatter());
})
.AddJsonFormatters();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseIISPlatformHandler();
app.UseMvc();
loggerFactory.AddConsole(minLevel: LogLevel.Verbose);
loggerFactory.MinimumLevel = LogLevel.Debug;
}
}