JD *_*vis 5 c# reflection system.reflection c#-8.0 default-interface-member
我有几个接口(IMapFrom和IMapTo),可以让我简化AutoMapper配置。每个接口都有MapTo和MapFrom方法的默认实现。我有一个单独的MappingProfile类,它使用反射来查找所有实现类,并调用它们的映射创建。
上述类看起来像这样:
public interface IMapFrom<T>
{
void MapFrom(Profile profile) => profile.CreateMap(typeof(T), GetType());
}
public interface IMapTo<T>
{
void MapTo(Profile profile) => profile.CreateMap(GetType(), typeof(T));
}
public class MappingProfile : Profile
{
public MappingProfile()
{
ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
}
private void ApplyMappingsFromAssembly(Assembly assembly)
{
var types = assembly.GetExportedTypes()
.Where(t => t.GetInterfaces().Any(i =>
i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IMapFrom<>) ||
i.GetGenericTypeDefinition() == typeof(IMapTo<>))))
.ToList();
foreach (var type in types)
{
var instance = Activator.CreateInstance(type);
var mapTo = type.GetMethod("MapTo");
var mapFrom = type.GetMethod("MapFrom");
mapTo?.Invoke(instance, new object[] {this});
mapFrom?.Invoke(instance, new object[] {this});
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果实现接口的类覆盖默认接口实现,则该类MappingProfile将按需要工作。但是,如果类仅依赖于默认实现,mapTo则方法mapFrom中的和ApplyMappingsFromAssembly均为 null。
例如,此类的映射将无法成功应用:
public class CreateJobCommand :
UpdateJobInputModel,
IMapFrom<UpdateJobInputModel>,
IMapTo<Job>,
IRequest<int>
{
}
Run Code Online (Sandbox Code Playgroud)
如果默认实现没有在继承类中重新实现,我如何获得默认实现?
根据 Kevin Gosse 对我的问题的评论,我研究了使用Microsoft 文档GetInterface().GetMethod()中看到的内容。
如果我采用这种方法,现在可以使用的结果代码如下所示:
public class MappingProfile : Profile
{
public MappingProfile()
{
ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
}
private void ApplyMappingsFromAssembly(Assembly assembly)
{
var types = assembly.GetExportedTypes()
.Where(t => t.GetInterfaces().Any(i =>
i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IMapFrom<>) ||
i.GetGenericTypeDefinition() == typeof(IMapTo<>))))
.ToList();
foreach (var type in types)
{
var instance = Activator.CreateInstance(type);
var mapTo = type.GetMethod("MapTo") ??
instance!.GetType()
.GetInterface("IMapTo`1")?
.GetMethod("MapTo");
var mapFrom = type.GetMethod("MapFrom") ??
instance!.GetType()
.GetInterface("IMapFrom`1")?
.GetMethod("MapFrom");
mapTo?.Invoke(instance, new object[] {this});
mapFrom?.Invoke(instance, new object[] {this});
}
}
}
Run Code Online (Sandbox Code Playgroud)