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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With