Skip to content

Commit

Permalink
Added design time DbContext factory.
Browse files Browse the repository at this point in the history
Added support appsettings.Local.json (settings specific to an individuals development environment).
Changed default database to LocalDb.
  • Loading branch information
jasontaylordev committed Oct 16, 2018
1 parent df84e99 commit 5f74aa7
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 237 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*.user
*.userosscache
*.sln.docstates
appsettings.Local.json

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace Northwind.Persistence.Infrastructure
{
public abstract class DesignTimeDbContextFactoryBase<TContext> :
IDesignTimeDbContextFactory<TContext> where TContext : DbContext
{
private const string ConnectionStringName = "NorthwindDatabase";
private const string AspNetCoreEnvironment = "ASPNETCORE_ENVIRONMENT";

public TContext CreateDbContext(string[] args)
{
return Create(Directory.GetCurrentDirectory(), Environment.GetEnvironmentVariable(AspNetCoreEnvironment));
}

protected abstract TContext CreateNewInstance(DbContextOptions<TContext> options);

private TContext Create(string basePath, string environmentName)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(basePath + "\\..\\Northwind..WebUI")
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.Local.json", optional: true)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();

var connectionString = configuration.GetConnectionString(ConnectionStringName);

return Create(connectionString);
}

private TContext Create(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentException($"Connection string '{ConnectionStringName}' is null or empty.", nameof(connectionString));
}

Console.WriteLine($"DesignTimeDbContextFactoryBase.Create(string): Connection string: '{connectionString}'.");

var optionsBuilder = new DbContextOptionsBuilder<TContext>();

optionsBuilder.UseSqlServer(connectionString);

return CreateNewInstance(optionsBuilder.Options);
}
}
}
3 changes: 3 additions & 0 deletions Northwind.Persistence/Northwind.Persistence.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
</ItemGroup>

<ItemGroup>
Expand Down
13 changes: 13 additions & 0 deletions Northwind.Persistence/NorthwindDbContextFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.EntityFrameworkCore;
using Northwind.Persistence.Infrastructure;

namespace Northwind.Persistence
{
public class NorthwindDbContextFactory : DesignTimeDbContextFactoryBase<NorthwindDbContext>
{
protected override NorthwindDbContext CreateNewInstance(DbContextOptions<NorthwindDbContext> options)
{
return new NorthwindDbContext(options);
}
}
}
233 changes: 0 additions & 233 deletions Northwind.WebUI/.gitignore

This file was deleted.

24 changes: 21 additions & 3 deletions Northwind.WebUI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Northwind.Persistence;
using Microsoft.EntityFrameworkCore;
using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace Northwind.WebUI
{
Expand All @@ -26,14 +27,31 @@ public static void Main(string[] args)
catch (Exception ex)
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
logger.LogError(ex, "An error occurred while migrating or initializing the database.");
}
}

host.Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.Local.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>();
}
}
27 changes: 27 additions & 0 deletions Northwind.WebUI/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:52467/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Northwind.WebUI": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:52468/"
}
}
}
Loading

0 comments on commit 5f74aa7

Please sign in to comment.