为依赖注入中的多个接口提供单一实现

Provide single implementation for multiple interfaces in dependency injection

我目前正在编写一个使用依赖项注入的 WPF 应用程序。

分为多个项目:

  1. WPF 应用程序本身
  2. 服务接口
  3. 上述服务的实施
  4. 其他与本题无关的内容

现在我有一个泛型接口,泛型类型是从 WPF 应用程序传入的。它也是在 WPF 应用程序中定义的,而不是在另一个可以被其他项目访问的库中定义的,所以除了 WPF 应用程序之外,我无法在其他任何地方访问该类型。

我希望能够以非通用方式访问通用接口的服务,但我该怎么做?

想象一下以下情况:

我的接口是这样定义的。一种是非通用基础版本,通用版本仅公开一个通用类型的对象。

public interface IService
{
    void DoStuff();
}

public interface IService<T> : IService
{
    T GenericData { get; }
}

我这样实现所述接口:

public class ServiceImplementation<T> : IService<T>
{
    public T GenericData { get; }

    public void DoStuff() { } // Some irrelevant implementation
}

当我将该类型的对象注入到 WPF 应用程序中定义的另一个服务中时,我显然可以访问泛型实现,因为我知道泛型类型。但是,当我想访问我不知道通用类型的另一个库中的服务时,我想访问该服务的非通用版本。

当作为单例添加到 ServiceCollection 时,如何确保为两个接口提供相同的对象?

class WpfOnlyObject
{
    // Irrelevant stuff
}

// In the App.xaml.cs
public void ConfigureServices(ServiceCollection services)
{
    services.AddSingleton<IService<WpfOnlyObject>, ServiceImplementation<WpfOnlyObject>>();
    services.AddSingleton<IService, ServiceImplementation<WpfOnlyObject>>();
}

如果这个问题已经回答了,我真的很抱歉,但我在 SO 上找不到合适的答案。

根据 canton7 的建议,我执行了以下操作并且效果很好。

// taken from the code in the question
public void ConfigureServices(ServiceCollection services)
{
    services.AddSingleton<IService<WpfOnlyObject>, ServiceImplementation<WpfOnlyObject>>();
    services.AddSingleton<IService>(serviceProvider => serviceProvider.GetRequiredService<IService<WpfOnlyObject>>());
}