Provide the AddKeyedDbContext extension method on Services
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
## 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
``` csharp
services.AddKeyedSingleton("memory");
services.AddKeyedSingleton("queue");
```
``` csharp
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.
``` csharp
services.AddKeyedDbContext("master", options =>
{
options.UseSqlServer(Configuration.GetConnectionString("Master"));
});
services.AddKeyedDbContext("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.
``` csharp
services.AddKeyedDbContext("db1", options =>
{
options.UseSqlServer(Configuration.GetConnectionString("Db1"));
});
services.AddKeyedDbContext("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.
Contributor guide
Assessment
This issue has not been assessed yet.