簡體   English   中英

使用ASP.NET Core DI注冊接口的通用和特定實現

[英]Register both generic and specific implementation of an interface with ASP.NET Core DI

我已經閱讀了Armen Shimoon的文章ASP.NET Core:Factory Pattern Dependency Injection ,我決定使用他建議的技術來解決我的ASP.NET Core DI問題。 我有一個通用的界面:

public interface IItemRepository<out T> where T : BaseItem

及其通用實現:

public class ItemRepository<T> : IItemRepository<T> where T : BaseItem

我將其注冊為:

services.AddSingleton(typeof(IItemRepository<>), typeof(ItemRepository<>));

但是對於Currency,我有一個具體的實現:

public class CurrencyRepository : ItemRepository<Currency>

(Curency屬於BaseItem類型。)我想要的是注冊

CurrencyRepository

對於

IItemRepository<Currency>

ItemRepository<T>

對於實現BaseItem的所有其他項目。 我創建了一個工廠類來完成這個:

public class ItemRepositoryFactory : IServiceFactory> where T : BaseItem
{
    private readonly ApplicationDbContext _context;

    public ItemRepositoryFactory(ApplicationDbContext context)
    {
        _context = context;
    }

    public ItemRepository Build()
    {
        if (typeof(T) == typeof(Currency))
            return new CurrencyRepository(_context) as ItemRepository;

        return new ItemRepository(_context);
    }
}

但我不知道如何用IServiceCollection注冊它。 或者也許我不是正確的方式?

您無法明確注冊。 ASP.NET Core DI意味着簡單,提供開箱即用的DI / IoC體驗,並且易於插入其他DI / IoC容器。

因此,內置IoC不提供自動注冊,裝配掃描,裝飾器或類的所有接口/子類型的注冊。

對於具體實現,有一個“解決方法”

services.AddScoped<IMyService,MyService>();
services.AddScoped<MyService>(provider => provider.GetService<IMyService>());

然后構造函數中的MyServiceIMyService都將接收該類的相同實例。

但這不適用於開放式泛型並且是一個manuell過程。 對於自動發現或注冊,您需要第三方IoC容器,例如Autofac,StructureMap等。

但是在您的具體示例中,應該足以在ConfigureServices方法中注冊IItemRepository<Currency>

services.AddScoped<IItemRepository<Currency>,CurrencyRepository>();

但實際上,如果將IItemRepository<Currency>注入到服務中,那么開放式泛型應該已經涵蓋了這種情況。

暫無
暫無

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

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