Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing AutoMapper in an Azure Function

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
        }
    }

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...

like image 324
Christophe Loeys Avatar asked Nov 29 '17 10:11

Christophe Loeys


1 Answers

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
    }
}

Or just make a static constructor on MapInitializer itself.

See also this answer.

like image 139
Mikhail Shilkov Avatar answered Oct 21 '22 01:10

Mikhail Shilkov