I would like to know the recommended approach to getting a connection string from a config file for my xUnit .net core test project.
I have set up a test project using the new Visual Studio 2017 xUnit Test project template for .net core. This project will run my integration tests that reference 2 different .net core class library projects - one of which will talk to the database using EF Core.
I understand that normally the connection string should not be set or accessed in a class library project - it should be the application that consumes the class library that should set the connection string.
However, in this case it appears that the xUnit test project is treated somewhat like a class library project. I have not seen any examples of how to set up some sort of config file and access that from the test project. How do I access the connection string from a config file so that my test project can consume my Datalayer class library project and pass in the appropriate connection string?
I was able to access the connection string from my xUnit test project by creating a DbOptionsFactory class that returns a DbContextOptions object initialized with a connection string that it reads from an appsettings.json configuration file.
This requires a dependency on Microsoft.Extensions.Configuration
public static class DbOptionsFactory
{
static DbOptionsFactory()
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var connectionString = config["Data:DefaultConnection:ConnectionString"];
DbContextOptions = new DbContextOptionsBuilder<MyDbContext>()
.UseSqlServer(connectionString)
.Options;
}
public static DbContextOptions<MyDbContext> DbContextOptions { get; }
}
appsettings.json
{
"Data": {
"DefaultConnection": {
"Name": "MyDbContext",
"ConnectionString": "connection string goes here"
}
}
}
When instantiating my DbContext I pass in the optionsBuilder object that has the connection string from the configuration file like so:
using (var context = new MyDbContext(DbOptionsFactory.DbContextOptions))
{
// access db here
}
Hope this helps anyone else that runs into the same issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With