防止其他项目需要依赖项

Prevent dependencies being required by other projects

我正在编写一个项目,它将在一项服务中封装多个日历 API(Google 日历、Outlook 等)。这将允许我集成可以映射到我们的领域模型的不同 APIs。但是,我遇到了所需依赖项 溢出 到其他项目的问题。这是一个例子:

我创建了一个通用的 class,它完成了从 API 模型到 我们的 模型的大部分工作和转换。这是一个例子:

public abstract class CalendarAPIBase<TEventType> : ICalendarAPI
{
    public CalendarEvent Get(string id)
    {
        if (string.IsNullOrEmpty(id))
            throw new ArgumentNullException("id");

        return Convert(GetEvent(id));
    }

    public List<CalendarEvent> GetAll()
    {
        List<CalendarEvent> result = new List<CalendarEvent>();

        List<TEventType> es = GetAllEvents();

        foreach (TEventType e in es)
            result.Add(Convert(e));

        return result;
    }

    protected abstract List<TEventType> GetAllEvents();
    protected abstract CalendarEvent Convert(TEventType obj);

    //More stuff below.
}

所以这是一件美妙的事情,任何继承 CalendarAPIBase 的东西都不需要做太多工作,除了 从 API 获取 数据,基础 class 将处理转换。

好的,这就是问题所在。我创建了一个 GoogleCalendarAPI class,它继承自 CalendarAPIBase。它传入 Event class,属于 NuGet 包 Google.Apis.Calendar.v3.

public class GoogleCalendarAPI : CalendarAPIBase<Event>

这里的问题是这个 class 暴露了 Event class,因此任何引用这个项目的东西也需要引用 Google.Apis.Calendar.v3。理想情况下,任何希望使用此服务的人都只需引用该项目,而不必担心安装其他 NuGet 包。

如何重组我的 classes 以防止这种情况发生?

解决这个问题最直接的方法是 Abstract factory 模式。

首先,您创建 CalendarAPIBase<TEventType> 及其所有后代 internal。所有 public 内容都必须集中在 public ICalendarAPI 界面中。

下一步是像这样介绍 public 类:

public static class GoogleCalendarAPIFactory 
{
    public static ICalendarAPI Instantiate( ....... ) 
    {
        .......
        return new GoogleCalendarAPI( ..... );
    }
}

工厂会将所有 TEventType 麻烦隐藏在库用户面前,因此他不需要添加包含 TEventType 实现的所有包。

我不确定如果直接在 Google.Apis.Calendar.v3.Event 中使用 类 是否可以避免引用第 3 方程序集你的代码。

但是,您可以使用 ILMerge 将第三方 API 合并到您自己的,这样您的程序集的依赖项将与您的程序集一起部署。

我通常在 post 构建事件中使用 ILMerge。 例如:

  • GoogleCalendarAPI项目建好后,合并GoogleCalendarAPI.dllGoogle.Apis.Calendar.v3.dll保存在"GoogleCalendarAPI_location\mergerd\GoogleCalendarAPI.dll"

  • 复制"GoogleCalendarAPI_location\mergerd\GoogleCalendarAPI.dll"到原来GoogleCalendarAPI.dll的位置并替换.

现在你已经得到了 GoogleCalendarAPI.dllGoogle.Apis.Calendar.v3。 现在每个引用 GoogleCalendarAPI.dll 的程序集都得到了。