有没有一种方法可以轻松地将不同的实现注入到应用程序的不同层中?

问题描述 投票:0回答:1

我想知道是否有一种简单的方法可以在 ASP.NET Core 中逐层确定接口的实现。

例如,拿这张图

  • 假设 DataAccess.Customer 和 DataAccess.Employee 都依赖于其存储库中的 IMySqlConnection。
  • 但是两层都需要不同的连接配置选项或实现

是否有一种简单的方法可以让应用程序层自动为所有潜在的 DataAccess.Customer 和 DataAccess.Employee 存储库注入不同的 IMySqlConnections?

或者有更好的方法来处理这个问题吗?

谢谢!

asp.net asp.net-core architecture software-design
1个回答
0
投票

如果您正在使用或可以升级到.NET 8,您可以使用新引入的功能,允许密钥服务注册。例如:

builder.Services.AddKeyed{Lifetime}<IMySqlConnections>("Customer", (sp, key) => ...);
builder.Services.AddKeyed{Lifetime}<IMySqlConnections>("Employee", (sp, key) => ...);

在达尔:

public class Customer 
{
    public Customer([FromKeyedServices("Employee")] IMySqlConnections connections)
    {
        // ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.