[英]Using `GetMethod` on class implementing an interface with a default method implementation returns null
我有几个接口( 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});
}
}
}
如果实现接口的类覆盖默认接口实现,则MappingProfile
类将按需要工作。 但是,如果类单纯依靠默认实现, mapTo
和mapFrom
在ApplyMappingsFromAssembly
方法都无效。
例如,此类不会成功应用其映射:
public class CreateJobCommand :
UpdateJobInputModel,
IMapFrom<UpdateJobInputModel>,
IMapTo<Job>,
IRequest<int>
{
}
如果没有在继承类中重新实现,如何获得默认实现?
根据 Kevin Gosse 对我的问题的评论,我研究了使用GetInterface().GetMethod()
如Microsoft 文档中所示。
如果我采用这种方法,现在可以运行的结果代码如下所示:
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});
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.