我完全不知道为什么我会得到映射异常。我创建了一个单例来加载我的所有配置文件。我通过从程序集中获取类型然后使用Activator.CreateInstance来实例化配置文件来加载我的配置文件。有时一些测试用例正在通过,有时候测试用例也会失败。从我可以推断出存在某种竞争条件,导致这个问题根本不应该发生我是否遗漏了别的东西?我也得到了TypeInitialization Exceptions。
public static class AutoMapperRestConfiguration
{
private static readonly object Sync = new object();
private static bool isInitialized = false;
public static void Configure()
{
lock (Sync)
{
if (!isInitialized)
{
Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Automapper initialized");
Mapper.Initialize(cfg =>
{
Mapper.Initialize(x => GetConfiguration(Mapper.Configuration));
});
Mapper.AssertConfigurationIsValid();
isInitialized = true;
}
}
}
private static void GetConfiguration(IConfiguration configuration)
{
var assemblies = new List<Assembly>();
assemblies.Add(typeof(SomeProfile).Assembly);
// assemblies.Add(typeof(SomeProfile2).Assembly);
assemblies.Add(typeof(SomeProfile3).Assembly);
foreach (var assembly in assemblies)
{
var profiles = assembly.GetTypes().Where(x => typeof(Profile).IsAssignableFrom(x));
foreach (var profile in profiles)
{
configuration.AddProfile((Profile)Activator.CreateInstance(profile));
}
}
}
}