Passing application's connection string down to a Repository Class Library in ASP.NET 5 using the IConfigurationRoot

后端 未结 7 1753
情话喂你
情话喂你 2020-12-08 19:51

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

7条回答
  •  有刺的猬
    2020-12-08 20:42

    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.

提交回复
热议问题