簡體   English   中英

如何注冊具有多個接口的服務並將該服務用作 ConfigureServices.Net Core 3.1 中的單個實例

[英]How to register a service having multiple interfaces and use that service as a single instance in ConfigureServices .Net Core 3.1

我有實現多個接口的服務; 例如

ServiceClass : IService1, IService2
{
// implementation
}

現在我需要在 ConfigureServices() 中注冊這個服務,這樣我就有一個 SerivceClass 實例,即使 IService1 或 IService2 是通過構造函數注入的,也可以使用這個實例。 例如,

public class SomeClass1: ISomeClass1
    {
      SomeClass1(IService1 service)
          {
           ...
          }
    }

public class SomeClass2 : SomeClass2
    {
      SomeClass2(IService2 service)
          {
           ...
          }
    }

我曾嘗試在 ConfigureServices() 中使用它的兩個接口注冊 ServiceClass,但它會創建多個實例。

ConfigureServices(){

...
services.AddSingleton<IService1, ServiceClass>();
services.AddSingleton<IService2, ServiceClass>();
services.AddSingleton<ISomeClass1>(
                x => new SomeClass1(
                    x.GetRequiredService<IService1>(),
                    ));

services.AddSingleton<ISomeClass2>(
                x => new SomeClass2(
                    x.GetRequiredService<IService2>(),
                    )); 
....
}

我需要找到一個解決方案,即使注入的接口不同,我也可以向 SomeClass1 和 SomeClass2 注入相同的實例。

解決此問題的一種方法是注冊實現 class,然后從中顯式解析多個接口:

services.AddSingleton<ServiceClass>();
services.AddSingleton<IService1, ServiceClass>(x => x.GetRequiredService<ServiceClass>());
services.AddSingleton<IService2, ServiceClass>(x => x.GetRequiredService<ServiceClass>());

例如, 這里有一個用於 HttpClientFactory 的方法示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM