使用单个接口注册多个实现 [英] Register multiple implementations with single interface

查看:65
本文介绍了使用单个接口注册多个实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以注册一个接口,该接口由多个具体类使用[simple-injector]而不使用模板接口来实现?

Is there a way to register a single interface which is implemented by more than one concrete class using [simple-injector] and without using template interface?

说我们有2个类 MyClass1 Myclass2 ,这两个类都实现了 IInterface1

say we have 2 classes MyClass1 and Myclass2 and both these classes are implementing IInterface1

现在,我们无法使用[简单注射器]

Now using [simple-injector] we were not able to do this

container.Register<IInterface1, Myclass1>();
container.Register<IInterface1, Myclass2>();

将现有接口转换为模板接口在现有代码库上有点困难。希望有一些简单的方法。

converting existing interface to template interface is kinda a hard job on the existing codebase. Hoping there is some easier out there.

推荐答案

您可以使用 RegisterCollection 方法(请参见文档:配置集合

You can register multiple implementation of the same interface with using the RegisterCollection method (see documentation: Configuring a collection of instances to be returned)

所以您需要编写:

container.Collection.Register<IInterface1>(typeof(Myclass1), typeof(Myclass2));

现在,简单注入器可以注入 Interface1 实现到您的构造函数中,例如:

And now Simple Injector can inject a collection of Interface1 implementation into your constructor, for example:

public class Foo
{
    public Foo(IEnumerable<IInterface1> interfaces)
    {
        //...
    }
}

或者您可以使用 GetAllInstances

var myClasses = container.GetAllInstances<IInterface1>();

这篇关于使用单个接口注册多个实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆