I have just started looking into .NET Core with Entity Framework. I have previously used .NET Framework with Ninject but I'm now trying to use the DI built into .NET Core.
I have a TestBase
class which my tests will derive from. I want this class to be responsible for creating and deleting a test database using [OneTimeSetUp]
and [OneTimeTearDown]
. The problem is that I don't seem to be able to figure out how to gain access to my DI services in the setup and teardown methods. These methods cannot have parameters and my TestBase
class must have a parameterless constructor so I can't get them from there either.
[SetUpFixture]
public partial class TestBase
{
protected IEFDatabaseContext DataContext { get; set; }
public TestBase(IEFDatabaseContext dataContext)
{
this.DataContext = dataContext;
}
[OneTimeSetUp]
public void TestInitialise()
{
this.DataContext.Database.EnsureCreated();
}
[OneTimeTearDown]
public void TestTearDown()
{
this.DataContext.Database.EnsureDeleted();
}
}
The above gives the following error:
TestBase
does not have a default constructor.
I may well be going about this the wrong way but this is how I've always done things in the past so please let me know if there is a better method when using .NET Core DI.
Startup
class for reference:
public class Startup
{
private readonly IConfiguration config;
public Startup(IConfiguration config)
{
this.config = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TestDataContext>(
options => options.UseSqlServer(this.config.GetConnectionString("TestConnectionString")),
ServiceLifetime.Singleton);
services.AddScoped<IEFDatabaseContext>(provider => provider.GetService<TestDataContext>());
}
}