问题
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?
回答1:
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));
}
来源:https://stackoverflow.com/questions/45412366/how-to-add-config-file-in-class-library-followed-by-connection-string-for-net