Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 builder.Build();

Throughout the MVC Web Application I can simply do

Startup.Configuration["Data:DefaultConnection:ConnectionString"] 

to get the conn string from the appsettings.json file.

How can I get the connection string specified in the ASP.NET 5 MVC appsettings.json passed down to my Repository Class Library using constructor injection?

UPDATE:
Here is the base repository that all other repositories inherit from (as you can see I have a hardcoded connection string in here for now):

public class BaseRepo {     public static string ConnectionString = "Server=MYSERVER;Database=MYDATABASE;Trusted_Connection=True;";      public static SqlConnection GetOpenConnection()     {         var cs = ConnectionString;         var connection = new SqlConnection(cs);         connection.Open();         return connection;     } } 

In my asp.net 5 web application in my appsettings.json file I have the following which is equivalent to adding a connection string to a web.config in a .net 4.5 webapp:

  "Data": {     "DefaultConnection": {       "ConnectionString": "Server=MYSERVER;Database=MYDATABASE;Trusted_Connection=True;"     }   } 

Additionally in my asp.net 5 web application I have the following default code in my Startup.cs which loads the sites configuration into a public property of type IConfigurationRoot:

 public IConfigurationRoot Configuration { get; set; } // Class Constructor         public Startup(IHostingEnvironment env)         {             // Set up configuration sources.             var builder = new ConfigurationBuilder()                 .AddJsonFile("appsettings.json")                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);              if (env.IsDevelopment())             {                 // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709                 builder.AddUserSecrets();             }              builder.AddEnvironmentVariables();             Configuration = builder.Build();         } 

Now in my asp.net web application if I would like to access any of the appsettings I can simple do the following: Startup.Configuration["Data:DefaultConnection:ConnectionString"]

But unfortunately I can't do this from my class library..

If someone wants to try and figure this out here are the steps to reproduce:

  1. Create a new ASP.NET 5 MVC Web App.
  2. Add another project of type Class Library (Package) to the project.
  3. Figure out a way to pass appsettings from the ASP.NET 5 MVC App to the Class Library

After updating I still can't quite get it. Here is my code:

public class BaseRepo {     private readonly IConfigurationRoot config;      public BaseRepo(IConfigurationRoot config)     {         this.config = config;     } } 

This class declaration does not work since BaseRepo requires a constructor param now.

public class CustomerRepo : BaseRepository, ICustomerRepo {     public Customer Find(int id)     {         using (var connection = GetOpenConnection())         {             ...         }     } } 
like image 836
Blake Rivell Avatar asked Jan 26 '16 13:01

Blake Rivell


Video Answer


1 Answers

on your Startup.cs file add the following method

public void ConfigureServices(IServiceCollection services) {     services.AddSingleton(_ => Configuration); } 

then update your BaseRepo class like this

public class BaseRepo {     private readonly IConfiguration config;      public BaseRepo(IConfiguration config) {         this.config = config;     }      public SqlConnection GetOpenConnection() {         string cs = config["Data:DefaultConnection:ConnectionString"];         SqlConnection connection = new SqlConnection(cs);         connection.Open();         return connection;     } } 
like image 184
Manos Pasgiannis Avatar answered Oct 06 '22 00:10

Manos Pasgiannis