我目前正在开发一个场景,需要Automapper使用IOC创建新实例。此外,我只需要在需求增加时注册Automapper的映射(因此我不使用概要文件)。为了达到同样的目的,我做了以下几点。
var cfg = new MapperConfigurationExpression();
cfg.ConstructServicesUsing(type =>
{
return CreateInstanceUsingIOC(type);
});
cfg.CreateMap<Model1, Model2>()
.ConstructUsingServiceLocator();
var config = new MapperConfiguration(cfg);
var mapper = config.CreateMapper();
var model1UsingIoC = CreateModel1UsingIoC();
model1UsingIoC.MyProfile = new Person();
model1UsingIoC.MyProfile.FirstName = "New First Name";
model1UsingIoC.MyProfile.LastName = "New Last Name";
model1UsingIoC.CommonProperty = "This wont be copied";
var model2b = mapper.Map<Model2>(model1UsingIoC);
但是,问题在于内部属性Model1.MyProfile。源和目标中的MyProfile实例看起来相同。
ReferenceEquals(model2b.MyProfile,model1UsingIoC.MyProfile) // True
此外,我想使用IoC创建每个用户定义的子属性。为此,我将ConstructServicesUsing语句添加为
cfg.ConstructServicesUsing(type =>
{
var instance = CreateInstance(type);
return ReassignProperties(instance);
});
其中,重新分配属性定义为
public static object ReassignProperties(object obj)
{
if (obj == null) return null;
Type objType = obj.GetType();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
// Check if its a collection
if (property.IsEnumerable())
{
if (property.GetValue(obj, null) is IEnumerable elems)
{
foreach (var item in elems)
{
ReassignProperties(item);
}
}
}
else
{
// If it is User Defined Type, Recursively loop again
if (property.PropertyType.Assembly == objType.Assembly)
{
var newValue = CreateInstance(property.PropertyType);
property.SetValue(obj, newValue);
var value = property.GetValue(obj);
ReassignProperties(value);
}
else
{
var propValue = property.GetValue(obj, null);
Console.WriteLine($"{property.Name} = {propValue}");
}
}
}
return obj;
}
但是,正如我们可以假设的那样,这也没有帮助,在映射时,相同的实例被复制到子属性上。是否有人可以指导我如何确保在使用Automapper时为用户定义的子属性创建新实例(即,创建新实例并复制值,除非类型为基元类型)?
更新001
按照Lucian的建议,我尝试创建一个自定义映射器,如下所示,并将其添加到映射注册表中。
public class NewInstanceMapper : IObjectMapper
{
public bool IsMatch(TypePair context) => true;
public static object CreateInstance(Type type)
{
try
{
var methodInfo = typeof(IoC).GetMethod(nameof(IoC.Get), BindingFlags.Public | BindingFlags.Static);
var genericMethodInfo = methodInfo.MakeGenericMethod(type);
return genericMethodInfo.Invoke(null, new object[] { null });
}
catch (Exception)
{
return Activator.CreateInstance(type);
}
}
public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, PropertyMap propertyMap, Expression sourceExpression, Expression destExpression, Expression contextExpression)
{
return Expression.Call(this.GetType(), nameof(CreateInstance), null, Expression.Constant(destExpression.Type));
}
}
并使用将其添加到MappingRegistry
var cfg = new MapperConfigurationExpression();
cfg.Mappers.Insert(0,new NewInstanceMapper());
但是,正如人们所猜测的,这创建了新实例,但没有复制值
附加说明
请注意,我希望实现的目标是
-
a) 每个特性值都会根据命名约定复制到目标
-
-
c) 点b包括嵌套属性、集合(集合中的每个元素都需要使用复制的ioc和子属性值创建)