如何删除两个几乎相同的应用程序的 IoC 容器中的重复项?

How can I remove the duplication in IoC containers for two nearly-identical applications?

我有两个应用程序(在同一个解决方案中)依赖同一个共享库(单独的项目)。这个共享库完成了大部分工作,并将一些服务作为接口依赖项。

我的每个应用程序的 IoC 容器看起来都一样,除了一个服务需要在两个应用程序之间有所不同。我怎样才能最大限度地减少 IoC 容器中的这种重复?

如果我正确地理解了问题(并考虑到在没有看到实际代码的情况下很难争论正确的解决方案),方法将是这样的。

假设您有下一个解决方案结构:

SharedLib(can be just dll/nuget)
   ...
AppOne(refs and DI's shared)
   ...
AppTwo(refs and DI's shared)
   ...

那么你需要做什么:

SharedLib
   ...
Shared.DI (refs SharedLib and package with your IoC container, and other stuff if needed)
   ...
AppOne (refs Shared.DI)
   ...
AppTwo (refs Shared.DI)
   ...

Shared.DI 中,您创建了一个名为 RegisterShared 的方法,它将处理所有注册并将从 AppOneAppTwo 调用。我建议这样:

public static RegistrationExtensions
{
    public static void RegisterShared(this YourIoCBuilder builder,
       Action<YourIoCBuilder> registerUniqueServiceAction)
    {
         // do the common stuff 
         registerUniqueServiceAction(builder);             
    }
}

您可以省略 registerUniqueServiceAction 并在之前或之后注册所需的服务,但我个人更喜欢更明确的 API 因此很明显,此方法不会注册 [=] 所需的所有内容=18=] 上班。还取决于您使用的 IoC 到底是什么,您可以为 registerUniqueServiceAction 提供更明显的签名,这样就很清楚实际需要什么。