Automapper Azure Functions

How To Use Automapper In Azure Functions

This Azure tutorial will discuss How To Use Automapper In Azure Functions.

How To Use Automapper In Azure Functions

Before discussing How To Use Automapper In Azure Functions, We should know what Automapper is. Exactly.

What is Automapper?

Automapper is an excellent library that helps to map the objects that belong to different types, which means the dissimilar types of objects. If you take an example, say you need to map your Data transfer Object to your Model objects, in that case, Automapper will help.

It saves lots of time and resources to do this type of functionality.

Automapper Installation

If you want to use the Automapper in your Azure function project, what you need to do is, you need to install the Automapper library to your Azure Function project. You can do the installation with the help of your Nuget Package Manager Console window.

To open the NuGet Package Manager console from your Visual Studio 2019, click on the tools —> Nuget Package Manager —> Package Manager Console

automapper azure functions

Now run the below command to install the Automapper to the project.

Install-Package AutoMapper
azure function automapper

How To Create Mappings Using AutoMapper

Let’s understand How to create Mappings using the AutoMapper. Consider we have two classes with different properties, as below

Below is my EmployeeModel class

public class EmployeeModel
    {
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }

I have one more class, EmployeeDTO, as below.

public class EmployeeDTO
    {
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }

Below is the code to create a map between these two types, EmployeeModel and EmployeeDTO

var map = new MapperConfiguration(stp => {
                stp.CreateMap<EmployeeModel,EmployeeDTO>();
            });

IMapper iMap = map.CreateMapper();
var src = new EmployeeModel();
var destn = iMap.Map<EmployeeModel,EmployeeDTO>(src);

Initializing AutoMapper In An Azure Function

We will discuss how to Initialize AutoMapper in an Azure Function. Consider the below example

public static class MappingSetup
    {
        public static void Start()
        {
           
           // Add Code for initialize mappings here
           
        }
    }

Here is the Azure Function. You can call the Automapper instance from the Static constructor.

public static class TsinfoDetails
{
    static TsinfoDetails()
    {
        MappingSetup.Start();
    }

    [FunctionName("MyNewFunction")]
    public static void Run([QueueTrigger("myqueue-items")]string myQueueItem, TraceWriter log)
    {             
        log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
    }
}

AutoMapper With Dependency Injection

We will discuss How AutoMapper will help us in the case of Dependency Injection. Using AutoMapper in your code will help you get a customized DTO object with only necessary information instead of getting the Whole object with some unnecessary information.

AutoMapper Profile

It is an excellent way to organize your mapping configurations with the help of Profiles. To implement that, what we need to do is we will create a class that inherits from Profile, and then we can provide the configuration related to the mapper inside the Constructor itself.

As you can see below the code, the TSINFODetails class inherits the Profiles that define the mapping details.

public class TSINFODetails : Profiles
{
    public TSINFODetails()
    {
        this.CreateMap<TsInfoBundle, TsInfoModel>()
            .ForMember(dst => dst.Id, m => m.MapFrom(src => src.Id))
            //////////
            ;
    }
}

The above TSINFODetails is registered with the help of the AddAutoMapper() extension method.

public class MapperModule : Module
{
    public override void Load(IServiceCollection myservices)
    {
        ////////////
        myservices.AddAutoMapper(Assembly.GetAssembly(this.GetType()));
        /////////
    }
}

How to inject IMapper at the Azure Function

Let’s see how to inject IMapper at the Azure Function level here. We have used the IFunctionFactory to register all the dependencies when the trigger is called.

public static class TsinfoDetails
{
    
    public static IFunctionFactory fct = new FunctionFactory<MapperModule>();

    [FunctionName(nameof(GetTsInfoEmpDetails))]
    public static async Task<IActionResult> GetTsInfoEmpDetails(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "Getname/{name}")] HttpRequest req,
        string name,
        ILogger log)
    {
        IActionResult result;
        try
        {
            /////////

            
            outrslt = await fct.Create<ITsInfoEmpDetails, ILogger>(log)
                                  .InvokeAsync<HttpRequest, IActionResult>(req, options)
                                  .ConfigureAwait(false);
            /////////
        }
        return outrslt;
    }
}

To give some more Idea, If you are using the ASP.NET Core, Below is the way to inject the AutoMapper.

myservices.AddAutoMapper(myprofAssembly1, myprofAssembly2);

Or, if you are using the Marker types

services.AddAutoMapper(typeof(myprofAssembly1), typeof(myprofAssembly2) );

Now you can inject the AutoMapper like below.

public class TSINFOEmployeesController {
	private readonly IMapper mapper1;

	public TSINFOEmployeesController(IMapper mapper2) => mapper1 = mapper2;

	//////
}

Along with ASP.Net core, you can also use the AutoMapper with AutoFac, Ninject, Castle Windsor, etc.

You can also check out the Automapper Tutorial for more information.

You may also like following the below Articles

Conclusion

Well, in this article, we have discussed How To Use Automapper In Azure Functions, What is Automapper?, Automapper Installation, How To Create Mappings Using AutoMapper, Initializing AutoMapper In An Azure Function, AutoMapper With Dependency Injection and discussed AutoMapper Profile and How to inject IMapper at the Azure Function Level, Azure Functions automapper, automapper profile dependency injection, Automapper Tutorial, Why use AutoMapper C#?, How do I use AutoMapper C#?, How to work with AutoMapper, Where to configure AutoMapper?, How to use projections in AutoMapper?, Best Practices AutoMapper, Hope you have enjoyed this Article !!!