Reputation: 5689
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!
Upvotes: 12
Views: 6806
Reputation: 476
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;
}
}
}
Upvotes: 1
Reputation: 553
Basically, you are trying to configure the Mapper at multiple places in your code, as I understand, you are trying to fix the issue by centralizing the configuration.
This issue could be resolved also through using the Instance API, where multiple (one per instance) configurations are possible (for plugin or more separated architectures) http://docs.automapper.org/en/stable/Static-and-Instance-API.html
Upvotes: 0
Reputation: 5458
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();
}
Upvotes: 13
Reputation: 2804
Try to use:
AutoMapper.Mapper.Configuration.AssertConfigurationIsValid();
It throws System.InvalidOperationException...Mapper not initialized. Call Initialize with appropriate configuration.
.
Upvotes: 9