IoC和抽象类

时间:2018-09-20 12:08:30

标签: c# oop inversion-of-control

我正在编写一项服务,该服务可对各种情况下公众发表的评论进行情感分析。为此,我创建了以下界面:

项目A:

public interface ISentimentEngine
{
    SentimentEngineServices SentimentEngineProvider {get;}
    ISentimentEngineResult AnalyseSentiment(ISentimentRequest request);
}

我还有一个抽象类,其中包含一些针对实际服务的具体实现的常用功能:

项目B:

public abstract class SentimentEngineBase
{
    protected abstract int MaximumRequests { get; }
    protected SentimentEngineBase(string configurationXml)
    {

    }
    protected abstract SentimentEngineServices SentimentEngineProvider { get; }
    protected abstract string SentimentEngineName { get; }

    protected abstract void ProcessClientConfiguration(string configuration);
    protected abstract void GetDefaultConfiguration();
}

上述抽象类与其他对象位于同一项目中,例如响应和请求实现,并且接口均位于楼梯模式的实现中的单独合同项目(A)中。

然后,各个实现在进一步的项目中:

项目C:

public class MicrosoftAzureTextAnalyticsSentiment : SentimentEngineBase, ISentimentEngine
{

我不喜欢的事情是,服务的具体实现将需要依赖于基本抽象类(项目B)以及接口(项目A),就像我为之创建的所有实现一样。每个服务提供商,例如Microsoft Azure文本分析,Google Cloud Natural Language,Amazon Comprehend等,都将在单独的项目中进行规划。

我想使用IoC并将接口注入到各种对象构造函数中:

选项是:

  1. 这一切都很好,没关系,不用担心,继续前进吧!
  2. 将基类分离到另一个项目D中。将其与其他类分离。
  3. 仅使用接口,将一些抽象方法移至接口; (但我真的不喜欢他们拥有公共财产,而且必须一直做腿工作)。
  4. 有其他方法吗?

对不起,这可能是你们的基本知识,我可能缺少一些明显的东西,但是我看不到树木的木头。

谢谢

斯图。

1 个答案:

答案 0 :(得分:1)

我认为这没关系。是的,实现该接口的项目C将取决于项目A和B,对于Google Cloud Natural Language而言,项目C'将取决于项目,对于Amazon Comprehend,它将取决于项目C'。但是,此SentimentEngineConsumer的项目E与之不同。

class SentimentEngineConsumer
{
    ISentimentEngine _engine;
    public SentimentEngineConsumer(ISentimentEngine engine)
    {
        _engine = engine;
    }

    ...

}

只想使用该接口就不需要项目B,C,C',C“,...。它可以只使用项目A。可以将其留给依赖项注入模块以链接任意一个C, C'或C”投影到E。