Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know if automapper has already been initialized?

Tags:

c#

automapper

Is there a way to know if automapper has already been initialized? For example:

AutoMapper.Mapper.IsInitialized(); // would return false
AutoMapper.Mapper.Initialize( /*options here*/ );
AutoMapper.Mapper.IsInitialized(); // would return true

Thanks!

like image 555
Gaspa79 Avatar asked Feb 23 '18 16:02

Gaspa79


People also ask

Where is AutoMapper configuration?

Where do I configure AutoMapper? ¶ Configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.

How does AutoMapper work internally?

How AutoMapper works? AutoMapper internally uses a great concept of programming called Reflection. Reflection in C# is used to retrieve metadata on types at runtime. With the help of Reflection, we can dynamically get a type of existing objects and invoke its methods or access its fields and properties.


2 Answers

In our particular case, we had multiple unit tests competing for the same instance of AutoMapper. Even if we used the Reset() method, it threw the error that it was already initialized. We solved the problem with a singleton instance that is inherited by each unit test class in our tests project.

public class UnitTestsCommon
{
    public static IMapper AutoMapperInstance = null;

    public UnitTestsCommon()
    {
        if(UnitTestsCommon.AutoMapperInstance == null){       
            Mapper.Initialize(AutoMapperConfiguration.BootstrapMapperConfiguration);
            AutoMapperInstance = Mapper.Instance;
        }
    }
}
like image 99
John Bonfardeci Avatar answered Oct 06 '22 19:10

John Bonfardeci


You could call Mapper.Reset(); before initializing your mapper. I do this when initializing my unit test classes:

[ClassInitialize]
public static void ClassInitializer(TestContext context)
{
    Mapper.Reset();
    AutoMapperDataConfig.Configure();            
}
like image 34
martinoss Avatar answered Oct 06 '22 20:10

martinoss