How get all registred dbContext in .net 8?

173 Views Asked by At

I would like do something like this, but contexts always null:

public DbCheck(IEnumerable<DbContext> contexts)

Context:

public class c1( DbContextOptions<c1> options ) : DbContext( options )

Registration:

    services.AddDbContext<c1>(      options => );
1

There are 1 best solutions below

0
Qiang Fu On BEST ANSWER

You could try below sample:
c1.cs (correct connectionstring)

    public class c1 :DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=192.168.2.68;Initial Catalog=test123;User ID=sa;Password=xxxxx;TrustServerCertificate=True");
        }
    }

c2.cs (wrong connectionstring)

    public class c2 : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Wrong string");
        }
    }

program.cs

builder.Services.AddDbContext<c1>();
builder.Services.AddDbContext<c2>();

Controller

    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IServiceProvider serviceProvider;

        public ValuesController(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }

        [HttpGet("test")]
        public void test()
        {
            var type = typeof(DbContext);
            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsAssignableFrom(p))
                .ToList();
       
            for (int i = 0; i < types.Count - 1; i++)
            {
                DbContext context_instance=(DbContext) serviceProvider.GetService(types[i]);

                   bool result=context_instance.Database.CanConnectAsync().GetAwaiter().GetResult();

                    Console.WriteLine(types[i].Name +" connect: "+ result);
            }           
        }
    }

Test result
enter image description here

enter image description here

Explain:
If you check all the services in the "serviceprovider", you will find c1 and c2 are not implement from "DbContext", So you couldn't find them by"DbContext" directly from services. But you could get them from assembly. (Unlike "apple" implement from "IFruit").
enter image description here