How To Use Automapper In Azure Functions

How To Use Automapper In Azure Functions

In this Azure tutorial, we will discuss How To Use Automapper In Azure Functions. Along with this, we will also discuss the below topics.

  • What is Automapper?
  • Automapper Installation
  • How To Create Mappings Using AutoMapper
  • Initializing AutoMapper In An Azure Function
  • AutoMapper With Dependency Injection
  • AutoMapper Profile
  • How to inject IMapper at the Azure Function Level

How To Use Automapper In Azure Functions

Before discussing How To Use Automapper In Azure Functions, We should have little idea on what is Automapper? exactly.

What is Automapper?

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

It saves lots of time and resource 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 you Visual studio 2019, click on the tools —> Nuget Package Manager —> Package Manager Console

Use Automapper In Azure Functions

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

Install-Package AutoMapper
Use Automapper In Azure Functions

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

Well, Here 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

Well, We will discuss How AutoMapper will help us in the case of Dependency Injection. When you are using the AutoMapper in your code, it will help you to 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 mapper inside the Constructor itself.

If you can see below code, the TSINFODetails class inheriting the Profiles that actually defines 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

Well, let’s see here How to inject IMapper at the Azure Function level. We have used the IFunctionFactory to register all the dependencies when the trigger is actually 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;
    }
}

Just to give some more Idea, If you are using the ASP.NET Core, Below is the way to inject the 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 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 we also discussed AutoMapper Profile and How to inject IMapper at the Azure Function Level. Hope you have enjoyed this Article !!!

Leave a Comment