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!
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.
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.
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 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.
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;
}
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With