PomeloFoundation / Pomelo.EntityFrameworkCore.MySql

Entity Framework Core provider for MySQL and MariaDB built on top of MySqlConnector
MIT License
2.68k stars 382 forks source link

How do I remove from IServiceCollection the types added by AddDbContextPool()? #1068

Closed lnaie closed 4 years ago

lnaie commented 4 years ago

Steps to reproduce

NA

The issue

For my asp.net core integration testing, I need to replace the types added by the services.AddDbContextPool() with in-memory types created by:

                services.AddDbContext<AppDbContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                });

What are the signature of these types in the IServiceCollection container? Or how would you suggest to do it?

Further technical details

MySQL version: MariaDb 10.4.12 Operating system: MacOS Catalina 10.15.3 Pomelo.EntityFrameworkCore.MySql version: 3.1.1 Microsoft.AspNetCore.App version: 3.1.3

Thanks

mguinness commented 4 years ago

This question would be better suited for https://stackoverflow.com/questions/tagged/ef-core or the https://github.com/dotnet/efcore repo since it's not provider specific.

lauxjpn commented 4 years ago

Take a closer look as Testing with InMemory: Avoid configuring two database providers. It shows how to accomplish what you want without having to replace anything.

In case AddDbContextPool() is an issue for you, you can always restrict its usage to non-test runs and just use AddDbContext() in test runs.

lauxjpn commented 4 years ago

@lnaie Where you able to solve your problem?

lnaie commented 4 years ago

Hi, I did sorted it out, google-ing it of course. :) Oh man, too often OS is shadowed by the time wasted in fixing edge cases. Anyways for my aspnet core integration tests, that are documented at Customize WebApplicationFactory, and that I'm using for a signalr backend with mariadb, into a VS for mac, my fix was to replace the code block suggested in the official sample:

            services.AddDbContext<AppDbContext>(options =>
            {
                options.UseInMemoryDatabase("InMemoryDbForTesting");
            });

with:

                services.AddTransient(x => new DbContextOptionsBuilder<AppDbContext>()
                    .UseInMemoryDatabase(databaseName: "InMemoryDbForTesting")
                    .ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))
                    .Options);

In my case, the exception was that the DbContextOptions<AppDbContext>, that's being used by the only constructor of AppDbContext, could not be resolved from the root of the DI container.

Again, this workaround was not needed for using a MS SQL or SQLite DB provider.

That's all I could say about. Thanks

lauxjpn commented 4 years ago

Thanks for sharing your solution!