4

I am working on n-tier application, where I have Data Access Layer. which is independent to any other application. I have create Class Library for .NET Core 1.1, I can see dependencies folder but not any config/JSON file. I want to know, Can I add AppSetting.JSON file in class library project? followed by how can I add connection string. I am aware to override ConfigureBuilder in DbContext class --> SQLServerConnection but I want to keep in separate config file and refer to these connection strings.

Also to note, This class library will not link to ASP.NET application directly

While searching on google, I have found following link https://www.stevejgordon.co.uk/project-json-replaced-by-csproj but my question remains, where and how I add connection string for Class Library project?

K.Z
  • 5,201
  • 25
  • 104
  • 240
  • `This class library will not link to ASP.NET application directly` then how does it run? Something must be hosting the library – Jamiec Jul 31 '17 at 10:51
  • I am intended to use web api, but keep the database access, dbContext and repository independent – K.Z Jul 31 '17 at 10:53
  • well, that's a "ASP.NET Application" and its there you put your config! – Jamiec Jul 31 '17 at 10:54
  • So you should be adding configuration in your web api project and not for class library. Typically config files are for hosting application and not for class libraries. – Pankaj Kapare Jul 31 '17 at 10:55
  • from architecture point of view, then how I keep data access layer separate – K.Z Jul 31 '17 at 10:57
  • Thanks, I look into details – K.Z Jul 31 '17 at 11:04

1 Answers1

6

You've kind of got this the wrong way round. You dont want to have a config file for your DAL assembly, you simply want your DAL to know nothing at all about configuration!

Typically, all you configure for a DAL is a conection string and this can easily be passed in on a constructor:

public class MyRepository : IMyRepository
{
    public MyRepository(string connectionString){ ... }
}

When you use this DAL in something like a webapi chances are you'll be using Dependency Injection - and it's here you would read the conn string from the web api's configuration

public void ConfigureServices(IServiceCollection services)
{
    var connectionString = Configuration.GetConnectionString("MyConnectionString");
    services.AddScoped<IMyRepository>(sp => new MyRepository(connectionString));
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193