のインターフェイスの一般的な実装と特定の実装の両方を登録しました。Armen Shimoonの記事ASP.NET Core: Factory Pattern Dependency Injectionを読んで、彼が提案した手法を使用してASP.NET Core DIの問題を解決することに決めました。ASP.NETコアDI
public interface IItemRepository<out T> where T : BaseItem
とその一般的な実装:
public class ItemRepository<T> : IItemRepository<T> where T : BaseItem
私はそれを登録します。
services.AddSingleton(typeof(IItemRepository<>), typeof(ItemRepository<>));
しかし通貨のために、私が持っている 私は一般的なインタフェースを持っています具体的な実装:
10(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に登録する方法がわかりません。あるいは、私はまったく正しい方法ではないでしょうか?
完全に動作します。ありがとうございますTseng –