Skip to content

Instantly share code, notes, and snippets.

@lowds
Created February 19, 2021 11:13
Show Gist options
  • Save lowds/d029bb8eefda07d0e18a04a7f7c42daa to your computer and use it in GitHub Desktop.
Save lowds/d029bb8eefda07d0e18a04a7f7c42daa to your computer and use it in GitHub Desktop.
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