I am porting from traditional .net mvc application to .netcore.
Original application flow:
OSMSelectController -> OSMDB_Loader.cs -> StatusController
where the connectionstring is read and DAL is initialized.
This connectionstring is coming from static class but when I debug the value is null in here:
WPSGlobalSettings.ToolboxConnString
I have a static class for reading connectionstring from appsettings.
WPSGlobalSettings
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);
...
}
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 another 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!