我正在尝试创建一个 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) 没有这样的事情,并且我没有找到太多关于如何准确执行此操作的信息.我正在考虑用 try catch 来包围 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!