[英]Register a generic interface with a non generic implementation in ASP.NET Core Dependency Injection
[英]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>());
然后构造函数中的MyService
和IMyService
都将接收该类的相同实例。
但这不适用于开放式泛型并且是一个manuell过程。 对于自动发现或注册,您需要第三方IoC容器,例如Autofac,StructureMap等。
但是在您的具体示例中,应该足以在ConfigureServices
方法中注册IItemRepository<Currency>
services.AddScoped<IItemRepository<Currency>,CurrencyRepository>();
但实际上,如果将IItemRepository<Currency>
注入到服务中,那么开放式泛型应该已经涵盖了这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.