New configuration system for .NET Core is really awesome. But in official stylyguides it always uses in the main ASP.NET Core app. But what if we have other apps in the solution? Or we need to share configuration settings between projects? Additional info in my blog-post.
It's even getting worse, when we want to use Migrations
from EF Core.
If we don't have parameter less constructor in our DbContext
, there is a need for implementing IDbContextFactory
.
And in this case we star to face off a problem with passing connection string
to our context.
Official documentation contains an example with hard-coded connection string
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace MyProject
{
public class BloggingContextFactory : IDbContextFactory<BloggingContext>
{
public BloggingContext Create()
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
}
}
}
I don't think, that this is a flexible and right way to do this kind of fabric.
So, with the solution has been written by me, it looks in the next way
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace MyProject
{
public class BloggingContextFactory : IDbContextFactory<BloggingContext>
{
public BloggingContext Create()
{
var configurationRoot = SettingsProvider.GetConfigurationRoot(new EnvironmentProvider());
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
//In my project I put "mainDb" to ConfigurationConstants class
optionsBuilder.UseSqlite(configurationRoot.GetConnectionString("mainDb"));
return new BloggingContext(optionsBuilder.Options);
}
}
}
There is the article with the alternative way for solving this problem. But I don't like it due to low flexibility of configuration settings.
Install .NET Core SDK
Open folder with Configuration.sln
in the shell.
Then
dotnet restore
dotnet build
Open folder with Configuraion.Test.csproj
in the shell.
Then
dotnet test