1

I have a layered architecture for a project as follows.

MyProject.Web           <-- ASP.NET Core app
MyProject.BusinessLogic <-- Class Library
MyProject.DataAccess    <-- Class Library

Web project references BusinessLogic, which in turn references DataAccess.

The connection string is stored in appsettings.json in Web project as follows.

{
  "ConnectionStrings": {
    "LocalDatabase": "Server=..."
  },
  // ...

  }
}

How do I get a connection string in the DataAccess project?

sakura-bloom
  • 4,524
  • 7
  • 46
  • 61
  • `appsettings.json` should be located in application's entry point. Which is web project. Read the connection string at startup and pass it to data layer. Sorry I don't see any problem yet. – Ilya Chumakov May 19 '17 at 17:15
  • That would mean to read connection string in `Web`, then pass it to `BusinessLogic`, then pass it to `DataAccess`. This does not look very good. – sakura-bloom May 19 '17 at 17:22
  • You could use DI to make it cleaner: register a DTO and resolve it in the data layer. For example http://stackoverflow.com/q/43679665/5112433 – Ilya Chumakov May 19 '17 at 17:46
  • @erdinger: You don't need to pass the connection string. You configure a `DbOptionsBuilder`, this is what happens behind `.AddDbContext` method. It is registered with DI and injected into the DbContext when its resolved (or you can do it manually by requesting DbOptionsBuilder via DI and pass it to your context (and modify it before if necessary). Ideally you don't need to pass it anyways, most cases are covered with AddDBContext inside startup.cs – Tseng May 19 '17 at 18:33
  • 1
    @Tseng, thanks. However, I'm not using EF, I'm using Dapper in the `DataAccess`. – sakura-bloom May 19 '17 at 19:21
  • You may wish to consider restructuring your application to follow the Dependency Inversion Principle and Clean Architecture. http://deviq.com/dependency-inversion-principle/ https://github.com/ardalis/cleanarchitecture It will be more amenable to DI then. – ssmith May 20 '17 at 00:32

1 Answers1

2

Try this:

public static IConfiguration Configuration { get; set; }

private string GetConnectionString()
{
    var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");

    Configuration = builder.Build();

    return Configuration.GetConnectionString("DefaultConnection");

}

Remember appsetting.json

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=((local));Database=database;Trusted_Connection=True;user id=xx;password=xxxx;"
  }
}
  • It works fine, but what if you want to have different connection string for different environment (Development/Production)? – Jam Aug 28 '21 at 14:32