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?

6
  • 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. Commented May 19, 2017 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. Commented May 19, 2017 at 17:22
  • You could use DI to make it cleaner: register a DTO and resolve it in the data layer. For example stackoverflow.com/q/43679665/5112433 Commented May 19, 2017 at 17:46
  • @erdinger: You don't need to pass the connection string. You configure a DbOptionsBuilder<TDbContext>, this is what happens behind .AddDbContext<T> 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 Commented May 19, 2017 at 18:33
  • 1
    @Tseng, thanks. However, I'm not using EF, I'm using Dapper in the DataAccess. Commented May 19, 2017 at 19:21

1 Answer 1

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;"
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works fine, but what if you want to have different connection string for different environment (Development/Production)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.