asp.net core - Convention based approach for configuring services based on Operating System in Startup.cs -
i created asp.net service using 1.0.0-rc1-update1 on coreclr (x64). so, service capable of running on supported operating systems; cool! service exposes simple "todo" api , uses entity framework 7.0 orm. persistence, employs sqlite db on linux , sql server db on windows.
i wondering if there convention based approach allow startup.cs handle differing service configurations various operating systems? example, ef configuration differs because uses sqlite on linux , sql server on windows.
the following article detail convention based approaches configuration, seems allow different methods higher level abstractions of "development", "staging", "production" environments: https://docs.asp.net/en/latest/fundamentals/environments.html
currently, injecting iruntimeenviroment in constructor of startup.cs , saving it. then, when configureservices invoked, check operatingsystem property of iruntimeenvironment , adjust ef configuration accordingly (my full startup.cs provided below)...
any guidance on other (or recommended) approaches appreciated.
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; } }
Comments
Post a Comment