Dotnet Core 依赖注入,如何注册同一类的多个实例

kkd*_*er7 5 dependency-injection .net-core

我想知道是否可以使用 dotnet core DI 框架中的构建来注册同一类的多个实例

例如,我有一个类ToDo向客户端发送消息。ToDo我想要具有不同注入配置对象的同一对象的 2 个实例。所以最后我将有两个独立的ToDo对象实例。

这可能吗?


编辑:

假设我有一个模式pub/sub

我有一个名为的泛型类MessageSubService.cs,其实现看起来像这样

public class ASBMessageSubService : ASBSubService, IASBSubService
{
       public ASBMessageSubService(..., IOptions<ASBSubOptions> options): base(options)
}
Run Code Online (Sandbox Code Playgroud)

因此,基于此,我需要创建多个 ASBMessageSubService。唯一不同的是IOptions传入的内容IOptions是内部访问。如果我使用 ,我将无法访问该属性provider.GetRequireServices<T>

我明白我能做到

service.AddSingleton<ASBMessageSubService, IASBSubService>
service.AddSingleton<ASBMessageSubService, IASBSubService>
service.AddSingleton<ASBMessageSubService, IASBSubService>
Run Code Online (Sandbox Code Playgroud)

这将为我注册 3 个不同的实例。问题是实现是相同的,我将无法通过 `nameof(ASBMessageSubService); 的类型来解决它。

我还可以注册一个deligate可以根据名称或类型解决它的位置,但这会遇到我上面描述的相同问题,实现类型将是相同的。

(我知道我可以使用像structuremap或 这样的库autofac,通过将它们注册为命名实例来完成此操作。但是我想在这个项目中避免使用像这样的第三方工具。)

对此有何建议?

谢谢你!

Jev*_*don 2

大卫·G 回答了这个问题。我将稍微扩展它以帮助您和其他人。

您可以注册多个类,可以作为它们本身,也可以作为接口:

例如

services.AddTransient<Todo>(provider => new Todo(configuration1));
services.AddTransient<Todo>(provider => new Todo(configuration2));
services.AddTransient<Todo>(provider => new Todo(configuration3));
...
services.AddTransient<ITodoWorker, NeedTodos>();
Run Code Online (Sandbox Code Playgroud)

然后对于依赖注入,依赖于IEnumerable<Todo>

public class NeedTodos : ITodoWorker
{
    public NeedTodos(IEnumerable<Todo> todos)
    {
        foreach (var todo in todos)
        {
            if (todo.Id == "configuration1")
            {
                // an idea if you need to find a specific Todo instance
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)