依赖于实现相同接口的两个对象的简单注入器 [英] Simple Injector with dependency on two objects that implement same interface

查看:126
本文介绍了依赖于实现相同接口的两个对象的简单注入器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序(通过ASP.NET Web API公开),其全部目的是消耗两个数据源,并揭示相同点和不同点。因此,API具有以下设置:

I'm writing an application (exposed via an ASP.NET web API) that's entire purpose is to consume two data sources, and expose the similarities and differences. So the API has the following setup:

public class FooController : WebAPI
{
    public FooController(IFooRepository repoFromSourceA, IFooRepository repoFromSourceB)
    {
        ...
    }
}

保持区分哪个源(不能互换SourceA和SourceB)似乎使 container.RegisterCollection(..)不可能(或非常危险)使用。此外,由于一个类同时使用这两种实现,因此Decorator似乎不合适。

Maintaining the distinction of which one is of which source (SourceA and SourceB cannot be interchanged) seems to make container.RegisterCollection(..) impossible (or very dangerous) to use. Further, since one class is consuming both implementations, Decorator seems to not be fitting.

那么,我如何设置这种依赖注入?

How, then, would I setup this dependency injection?

推荐答案

您遇到的问题很常见。当从依赖注入开始时,许多开发人员为此感到困惑。处理此问题时,找出是否违反 Liskov替代原则(LSP)始终很重要,因为何时您这样做时,应该改为使用两个单独的接口。永远不要忘记:接口不仅仅是方法签名。

The question you have is a very common one. Many developers struggle with this, when starting with Dependency Injection. When dealing with this, it is always important to find out whether you are violating the Liskov Substitution Principle (LSP), because when you do, you should instead use two separate interfaces. Never forget: an interface is more than just the method signatures. It is a contract of how implementations of that contract behave and what they return.

您的评论似乎表明您没有违反LSP,因为它们的行为是相同的,它们可以彼此交换(这可能会破坏应用程序,但不会破坏用户)。

Your comment seems to indicate that you are not violating the LSP, since their behavior is identical and they can be swapped for one another (it might break the application, but it will not break the consumer).

在Simple Injector中处理此问题的方法是使用<使用 RegisterConditional 基于上下文的注入 c>方法。例如:

The way to handle this in Simple Injector is by using context based injection using the RegisterConditional methods. For instance:

container.RegisterConditional<IFooRepository, FooRepoA>(
    c => c.Consumer.Target.Parameter.Name.Contains("SourceA"));
container.RegisterConditional<IFooRepository, FooRepoB>(
    c => c.Consumer.Target.Parameter.Name.Contains("SourceB"));

此处 RegisterConditional 方法提供了断言将依赖项注入到的使用者的构造函数参数的名称包含 SourceA或 SourceB。

Here the RegisterConditional method is supplied with a predicate that constructor parameter of the consumer where the dependency is injected into, has a name that contains either "SourceA" or "SourceB".

这篇关于依赖于实现相同接口的两个对象的简单注入器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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