I am porting from traditional .net mvc application to .netcore.
I have a static class for reading connectionstring from appsettings.
public static class WPSGlobalSettings{ public static NpgsqlConnectionStringBuilder ToolboxConnString = build_conn_str(ToolboxDatabaseName);private static NpgsqlConnectionStringBuilder build_conn_str(string dbname) { string dbSetting = ConfigurationHelper.config.GetSection("ConnectionStrings")["DefaultConnection"]; ... }}
Controller
public class StatusController : Microsoft.AspNetCore.Mvc.ControllerBase{ protected StatusDAL status_dal = new StatusDAL(WPSGlobalSettings.ToolboxConnString);}
Here it gives type exception, wpsglobalsettings was not initialized and toolboxconnstring is null.
I have tried adding it as singleton to Startup but then i get
static types cannot be used as type arguments
Startup.cs
public void ConfigureServices(IServiceCollection services){ services.AddSingleton<IConfiguration>(Configuration); services.AddControllersWithViews(); services.AddSingleton<WPSGlobalSettings>(); ConfigurationHelper.Initialize(Configuration);}public void Configure(IApplicationBuilder app, IWebHostEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } WPSGlobalSettings.Configure(env); ...}
A similar application seems to work fine the same way.
Edit:
I have removed following from Startup.cs
services.AddSingleton<WPSGlobalSettings>();
Also, introduced DI as follows
protected StatusDAL status_dal;//= new StatusDAL(WPSGlobalSettings.ToolboxConnString);public StatusController(IConfiguration config) { status_dal = new StatusDAL(config.GetConnectionString("toolboxConnectionStrWPS")); }
Now the problem is older code calls controller constructor from another class as follows:
OSMDB_Loader.cs
public StatusAck LoadOSMSections(OsmLoadRequest request) { StatusAck statusack = new StatusController().PostStatusRecord(); }
Therefore I also added simple constructor in StatusController:
public StatusController() { }
but now ofcourse status_dal is always null
Something is not quiet right!