Skip to content

Provide the AddKeyedDbContext extension method on Services #34591

@bit365

Description

@bit365

Keyed services new features

Starting with .NET 8, there is support for service registrations and lookups based on a key, meaning it's possible to register multiple services with a different key, and use this key for the lookup.

See: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#keyed-services

services.AddKeyedSingleton<IMessageWriter, MemoryMessageWriter>("memory");
services.AddKeyedSingleton<IMessageWriter, QueueMessageWriter>("queue");
public class ExampleService
{
    public ExampleService([FromKeyedServices("queue")] IMessageWriter writer)
    {
        // Omitted for brevity...
    }
}

DbContext type needs to be enhanced

Provides the AddKeyedDbContext extension method on DbContext for injecting different configurations of the same type of DbContext. In some scenarios, such a design is required. For example, the following scenario.

Scene 1 database master-slave separation

The master database is used to write data, the slave database is used to read data.

services.AddKeyedDbContext<MyDbContext>("master",  options =>
{ 
    options.UseSqlServer(Configuration.GetConnectionString("Master"));
});

services.AddKeyedDbContext<MyDbContext>("slave",  options =>
{ 
    options.UseSqlServer(Configuration.GetConnectionString("Slave"));
});

Scene 2 database partition

For business situations with increasing data volume, consider sharding storage, where the database structure is the same but stored in different instances.

services.AddKeyedDbContext<MyDbContext>("db1",  options =>
{ 
    options.UseSqlServer(Configuration.GetConnectionString("Db1"));
});

services.AddKeyedDbContext<MyDbContext>("db2",  options =>
{ 
    options.UseSqlServer(Configuration.GetConnectionString("Db2"));
});

About compatibility

Providing the AddKeyedDbContext extension method for DbContext does not affect the original system and is only a type enhancement without disruptive changes.

Thank you, thank you very much.

Metadata

Metadata

Assignees

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions