I have an ASP.NET 5 MVC Web Application and in Startup.cs I see that the public property
IConfigurationRoot Configuration
is being set to
A slightly different approach would be to make a static class in your Class Library on which you call a method from the Configure(..)
-method in Startup.cs
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
ConnectionManager.SetConfig(Configuration);
}
In this case, I've added Configuration as a Singleton in ConfigureServices
:
services.AddSingleton(_ => Configuration);
My ConnectionManager
looks like this:
public class ConnectionManager
{
private static IConfiguration currentConfig;
public static void SetConfig(IConfiguration configuration)
{
currentConfig = configuration;
}
///
/// Get a connection to the database.
///
public static SqlConnection GetConnection
{
get
{
string connectionString = currentConfig.GetConnectionString("MyConnection");
// Create a new connection for each query.
SqlConnection connection = new SqlConnection(connectionString);
return connection;
}
}
}
This may or may not have some issues regarding object lifetimes and such, and I'm certainly no fan of static
classes but as far as I can tell it's a viable approach. Instead of passing Configuration
you could even extract the ConnectionString
from the config-file and send only that.