1

I am completely clueless as to why I am getting the mapping exceptions. I have created a singleton to load all my profiles. I am loading my profiles by getting the type from the assembly and then using Activator.CreateInstance to instantiate the profiles. Sometimes some test cases are passing, sometimes the very same test cases are failing. From what I can infer there is some sort of a race condition, which is leading to this issue which shouldn't happen at all Am I missing something else? I am getting TypeInitialization Exceptions too.

    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));
            }
        }
    }
}
Sharthak Ghosh
  • 576
  • 1
  • 9
  • 22

0 Answers0