【问题标题】:Initializing AutoMapper in an Azure Function在 Azure 函数中初始化 AutoMapper
【发布时间】:2017-11-29 10:56:51
【问题描述】:

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

MapInitializer.cs:

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

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

Function.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 正确执行此操作,因为通常您会在 App Startup 中对其进行初始化,但我认为 Azure Functions (CMIW) 没有这样的事情,并且我没有找到太多关于如何准确执行此操作的信息。我正在考虑用 try catch 包围 Activate() 调用,并记录一个配置已加载的警告,但这似乎不是很干净......

【问题讨论】:

    标签: c# azure initialization automapper azure-functions


    【解决方案1】:

    您只需拨打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

    【讨论】:

    • 这很好用,谢谢!我以前没有见过/使用过静态构造函数,很有趣!
    • @Mikhail 感谢您向我介绍静态构造函数 :)
    • 如何在函数“ProcessQueue”中使用在静态构造器 ProcessQueueForIntercom() 中初始化的映射器?如何从函数中获取“_mapper”实例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多