简体   繁体   English

我怎么知道 automapper 是否已经初始化?

[英]How do I know if automapper has already been initialized?

Is there a way to know if automapper has already been initialized?有没有办法知道 automapper 是否已经初始化? For example:例如:

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

Thanks!谢谢!

You could call Mapper.Reset(); 你可以调用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();            
}

Try to use: 尝试使用:

AutoMapper.Mapper.Configuration.AssertConfigurationIsValid();

It throws System.InvalidOperationException...Mapper not initialized. Call Initialize with appropriate configuration. 它抛出System.InvalidOperationException...Mapper not initialized. Call Initialize with appropriate configuration. System.InvalidOperationException...Mapper not initialized. Call Initialize with appropriate configuration. .

In our particular case, we had multiple unit tests competing for the same instance of AutoMapper.在我们的特殊情况下,我们有多个单元测试竞争 AutoMapper 的同一个实例。 Even if we used the Reset() method, it threw the error that it was already initialized.即使我们使用了 Reset() 方法,它也会抛出它已经初始化的错误。 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;
        }
    }
}

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. 基本上,您正试图在代码中的多个位置配置Mapper,据我所知,您正试图通过集中配置来解决问题。

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 这个问题也可以通过使用Instance API解决,其中多个(每个实例一个)配置是可能的(对于插件或更多分离的体系结构) http://docs.automapper.org/en/stable/Static-and-Instance- API.html

You could also wrap your Initialization in a Try/Catch. 您还可以在Try / Catch中包装初始化。 This catches and squashes any error. 这会捕获并压制任何错误。

private void InitializeMapper()
    {
        try
        {
            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile<MyProfile>();
            });
        }
        catch
        {

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM