c# - 在 Azure 函数中初始化 AutoMapper

标签 c# azure initialization automapper azure-functions

我正在尝试创建一个 Azure 函数,在其中使用 AutoMapper 的一些代码。我对 C#、Azure 和 AutoMapper 还很陌生,在寻找初始化 AutoMapper 配置的正确方法时遇到了一些困难。

MapInitializer.cs:

public static class MapInitializer
    {
        public static void Activate()
        {
            Mapper.Initialize(cfg =>
            {
                // initialize mappings here
            });
        }
    }

然后在我的函数中,我尝试执行以下操作:

函数.cs:

public static class ProcessQueueForIntercom
    {

        [FunctionName("ProcessQueue")]
        public static void Run([QueueTrigger("messages")]string myQueueItem, TraceWriter log)
        {
            MapInitializer.Activate(); 

            // rest of the code
        }
    }

现在的问题是,我第一次用这个函数处理消息时,一切都很顺利,代码按照我的预期运行。但是,从第二次开始,我收到一条错误消息,指出我的配置已初始化。但我真的不知道如何使用Azure Function正确执行此操作,因为通常您会在应用程序启动中初始化它,但我不认为Azure Functions(CMIW)有这样的东西,并且我没有找到太多关于如何具体执行此操作的信息。我正在考虑用 try catch 包围 Activate() 调用,并记录一个配置已加载的警告,但这看起来不太干净......

最佳答案

您只需调用Activate一次。您可以通过静态构造函数来完成此操作:

public static class ProcessQueueForIntercom
{
    static ProcessQueueForIntercom()
    {
        MapInitializer.Activate();
    }

    [FunctionName("ProcessQueue")]
    public static void Run([QueueTrigger("messages")]string myQueueItem, TraceWriter log)
    {             
        // rest of the code
    }
}

或者只是在 MapInitializer 本身上创建一个静态构造函数。

另请参阅this answer .

关于c# - 在 Azure 函数中初始化 AutoMapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47551125/

相关文章:

python - Azure 数字孪生 Python API - 创建了模型孪生,但无法检索它

java - 为什么强制初始化静态最终变量?

c# - Code First - 自引用一对多关系

c# - 从 C# 运行 vbs Sub

azure - 您能举个例子解释一下 Microsoft Azure 中的 Append Blob 吗?

java - GUI 中的延迟初始化与急切初始化

c++ - const 变量的初始化

c# - Visual Studio 2015 调试烦人的盒子

c#在SplitContainer中使用TreeView控件改变内容

azure - 使用 Azure 资源管理器模板输出 IotHub 端点