-1

It seems that many .net tutorials storing connection strings are very simple projects not using a separate data access layer, or are fairly old.

What is the current best practice for storing a connection string in a c# project (I'm using a web API) that has a class library for data access separate from the main project? Should the connection strings be located in an appsettings.json within the class library, or are they required to reside in the main project, to be passed into the data access library?

Thanks!

David Mays
  • 466
  • 4
  • 14

1 Answers1

1

If the library is for only talking to one specific address and it is likely to be stable then it can make sense to hardcode it into the library.

On the other hand if the library can be used for multiple addresses then it is best to pass it in from the main project.

An approach that can work for both is to have a default address hardcoded, while still allowing developers to override it when using the library. A very simple example would be:

class MyApiLibrary
{
    MyApiLibrary(string address = "https://example.com/api/")
    {
        // Code
    }
}