-
-
Save lowds/d029bb8eefda07d0e18a04a7f7c42daa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.EntityFrameworkCore; | |
using Microsoft.Extensions.DependencyInjection; | |
using Xunit; | |
namespace EfCoreExperiments | |
{ | |
public class UnitTest1 | |
{ | |
[Fact] | |
public void RequestDbContextFromServices() | |
{ | |
var services = new ServiceCollection() | |
.AddEntityFrameworkInMemoryDatabase() | |
.AddDbContext<TestDbContext>(options => options.UseInMemoryDatabase("test database")) | |
.BuildServiceProvider(); | |
// with two constructors available this uses the one that takes DbContextOptions | |
var dbContext = services.GetRequiredService<TestDbContext>(); | |
Assert.NotNull(dbContext); | |
} | |
[Fact] | |
public void RequestDbContextFactoryFromServices() | |
{ | |
var services = new ServiceCollection() | |
.AddEntityFrameworkInMemoryDatabase() | |
.AddDbContextFactory<TestDbContext>(options => options.UseInMemoryDatabase("test database")) | |
.BuildServiceProvider(); | |
// this throws System.InvalidOperationException, Multiple constructors accepting all given argument types have been found in type 'EfCoreExperiments.TestDbContext'. There should only be one applicable constructor. | |
var factory = services.GetRequiredService<IDbContextFactory<TestDbContext>>(); | |
// code never gets this far | |
var dbContext = factory.CreateDbContext(); | |
Assert.NotNull(dbContext); | |
} | |
} | |
public class TestDbContext : DbContext | |
{ | |
/// <summary> | |
/// For use with EF core tooling | |
/// </summary> | |
public TestDbContext() | |
{ | |
} | |
/// <summary> | |
/// For configuring via options | |
/// </summary> | |
/// <param name="options"></param> | |
public TestDbContext(DbContextOptions<TestDbContext> options) | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment