通过通用接口/抽象类实现使.NET Core DI自动解析类
.NET Core中是否有一种方法可以注册通用接口,并使其解析与某个实现相匹配的类。
例如,我有以下界面:
public interface IMapper { }
我还有一个抽象类:
public abstract class Mapper : IMapper { protected Mapper() { // some generic stuff } public abstract TTo Map(TFrom); }
然后我可以创建一个这样的实现:
public class UserMapper : Mapper { public override Entity.User Map(Domain.User from) { // do mapping } }
有没有办法,使用默认的.NET Core DI注册IMapper
,让它自动解析类?
因此,如果我在代码中的某个地方执行此操作:
class SomeClass { public SomeClass(IMapper mapper) {} }
它以某种方式知道它应该解析类UserMapper
?
原因是手动注册每个映射器有点冗长,特定于实现。 所以我希望Microsoft.DependencyInjection
足够智能,以某种方式自动解决其实现。
您当前设计的唯一方法是使用Reflection:
Assembly assembly = typeof(UserMapper).Assembly; foreach (var type in assembly.GetTypes() .Where(t => t.IsClass && !t.IsAbstract)) { foreach (var i in type.GetInterfaces()) { if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapper<,>)) { // NOTE: Due to a limitation of Microsoft.DependencyInjection we cannot // register an open generic interface type without also having an open generic // implementation type. So, we convert to a closed generic interface // type to register. var interfaceType = typeof(IMapper<,>).MakeGenericType(i.GetGenericArguments()); services.AddTransient(interfaceType, type); } } }
注意:您可以通过在
IServiceCollection
上创建一个扩展方法来AddTransient
,其中AddSingleton
AddTransient
,AddSingleton
等的各种重载。
如果更改设计,请使用非抽象generics作为实现类型:
public class Mapper : IMapper { //... }
然后你可以像这样注册:
services.AddTransient(typeof(IMapper<,>), typeof(Mapper<,>));
- 有没有办法在.NET Core中只使用一个文件来运行控制台应用程序?
- 在dotnet核心中读取json文件时出错“已达到inotify实例数量的已配置用户限制(128)”
- 如何从.net核心中的appsettings.json中提取列表
- 将Env Conn字符串注入.NET Core 2.0 w / EF Core DbContext中的不同类lib比启动prj并实现IDesignTimeDbContextFactory
- 在.NET Core项目中找不到System.ServiceModel
- 使用配置调用AddDbContext,但上下文类型“MyContext”仅声明无参数构造函数?
- 正文的签名和方法实现中的声明不匹配
- 如何在Entity Framework Core 2中播种?
- 运行`serviceProvider.GetService ();`时,.Net core 2.0控制台程序得到空值。