在Azure函数中初始化AutoMapper [英] Initializing AutoMapper in an Azure Function

查看:79
本文介绍了在Azure函数中初始化AutoMapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Azure函数,其中在AutoMapper中使用了一些代码.我是C#,Azure和AutoMapper的新手,在查找初始化AutoMapper配置的正确方法时遇到了一些麻烦.

I am trying to create an Azure function in which I am using some code with AutoMapper. I am quite new to C#, Azure and AutoMapper and I'm having some trouble finding the correct way of initializing my AutoMapper configuration.

MapInitializer.cs:

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

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

Then in my function, I am trying to do the following:

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)有这种功能,并且我找不到有关如何准确执行此操作的太多信息.我当时正在考虑仅用尝试捕获来包围Activate()调用,并仅记录一条警告,指出配置已加载,但这似乎不是很干净...

Now the problem is, the first time I processed a message with this function, everything went smoothly and the code ran as I expected. However, from the second time on, I get an error saying my configuration is already initialized. But I don't really have an idea on how to do this properly with an Azure Function, since normally you would initialize this in the App Startup, but I don't think there is such a thing for Azure Functions (CMIW), and I'm not finding much information about how to exactly do this. I was thinking about just surrounding the Activate() call with a try catch and just log a warning that the configuration is already loaded, but that doesn't seem very clean...

推荐答案

您只需调用一次Activate.您可以通过静态构造函数来做到这一点:

You only need to call Activate once. You can do it from a static constructor:

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本身上创建一个静态构造函数.

Or just make a static constructor on MapInitializer itself.

另请参见此答案.

这篇关于在Azure函数中初始化AutoMapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆