How To Use Automapper In Azure Functions

How To Use Automapper In Azure Functions

This Azure tutorial 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
  • Automapper Tutorial
  • Why use AutoMapper C#?
  • How do I use AutoMapper C#?
  • How to work with AutoMapper
  • Where to configure AutoMapper?
  • What if the source and destination property names are different?
  • When the names are different how to use automapper?
  • How to use projections in AutoMapper?
  • Best Practices AutoMapper

How To Use Automapper In Azure Functions

Before discussing How To Use Automapper In Azure Functions, We should know what is Automapper? 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 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 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 you 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
automapper dependency injection

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

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

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

Automapper Tutorial

The automapper is a mapping or mapper between two objects, or you can consider it an object-object mapper. It is an excellent feature that helps to map the different properties of two different objects by converting an input object of one particular type to the output object of another type. The automapper is considered to be one of the important concepts in C#.

Automapper Tutorial

Why use AutoMapper C#?

AutoMapper is an excellent feature that provides you a wonderful opportunity to provide a few configurations of mapping between two objects of different types that helps to lead to the segregated models and can affect the object types in that particular layer in case of multilayer scenarios and can help you to avoid the conflict.

Behind The Scenes

Behind the scenes, Automapper uses the programming concept called Reflection that helps you to get the type of object from an existing object dynamically, and that helps to access its properties easily.

How do I use AutoMapper C#?

To work with the automapper, the first thing is we need the object type of the source and destination. Automapper best fits in the scenario where for example, you have a member in the source named “Address.” This will be mapped automatically with the name “Address”.

It’s always better to keep the source and destination object names the same while using the Automapper.

Another good thing is Auto mapper will ignore the null reference exceptions when it maps the source object with the object of your destination.

How to work with AutoMapper

Let’s consider we have two objects, Students and StudentsDTO. We will map the properties of the Students with the properties of the StudentDTO.

public class Students
    {
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }
public class StudentsDTO
    {
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }

Below are the steps we need to follow to work with the Automapper.

Installation of the AutoMapper library

The first step is to install the automapper library to use the automapper feature in your application. You can easily do the installation using the Nuget Package Manager Console window. We have already discussed the installation. Check out the automapper installation here.

Configuring the AutoMapper C#

Once you have installed the automappaer library and the types are ready, we can configure the automapper using the MapperConfiguration class. One important point to note is that we can create only one instance of the MapperConfiguration class per the App domain.

Below is the syntax to create the instance of the MapperConfiguration class.

var config = new MapperConfiguration(cfg => cfg.CreateMap<source, Destination>());

If we consider the Students and StudentsDTO class, the syntax will be like the below

var config = new MapperConfiguration(cfg => cfg.CreateMap<Students, StudentsDTO>());

Using AutoMapper C#

Now, let’s see, using the autoMapper C#, how it will be

Create mappings using AutoMapper

var myconfig = new MapperConfiguration(cfg => cfg.CreateMap<source, Destination>());

var mapper = myconfig.CreateMapper();
// or
var mapper = new Mapper(myconfig);
StudentsDTO dto = mapper.Map<StudentsDTO>(Students);

Where to configure AutoMapper?

As discussed above, you should do the automapper configuration once per app domain and keep the automapper configuration code in the startup class. For example, if you consider an ASP.net application, then it should be Global.asax file.

What if the source and destination property names are different?

It is always a best practice to keep the property name the same in source and destination if you want to implement the automapper feature. At the same time, if the name of the properties in the source differs from the name of the properties in the destination, it is also possible to implement the automapper feature.

When the names are different how to use automapper?

An easy way to implement the automapper feature in the scenario is when the name of the properties in the source is different than the property name in the destination.ForMember option.

For an example, consider the below Students and StudentDTO class

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

and the StudentDTO class is as below

public class StudentsDTO
    {
        public string FName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }

In this example, you can see that the first property name in the Students(Source) class is FirstName, and in the StudentsDTO(Destination) class is FName. If we have to implement the automapper feature in this scenario, the implementation will be like below.

 //Initializing the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Students, StudentsDTO>()
                    .ForMember(dest => dest.FName, act => act.MapFrom(src => src.FirstName))

This is how to do Mapping to Properties with different Names.

AutoMapper Examples

Now let’s see an example of the automapper with the actual value. Let’s take the same example of the Students

using System;
using AutoMapper;
namespace TestAutoMapper
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initializing the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Students, StudentsDTO>()
                    .ForMember(dest => dest.FName, act => act.MapFrom(src => src.FirstName)

            //Instanciating the source
            Students st = new Students
            {
                FirstName
 = "Rajkishore",
                LastName
 = "Sahoo"
              
            };

            //Use automapper
            var mapper = new Mapper(config);
            var stDTO = mapper.Map<StudentsDTO>(st);
            //OR
            //var stDTO2 = mapper.Map<Students, StudentsDTO>(st);

            Console.WriteLine("FirstName:" + stDTO.FirstName + ", LatName:" + stDTO.Salary);
            Console.ReadLine();
        }
    }
    
    public class Students
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
    }

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

When the Property names are different

using System;
using AutoMapper;
namespace TestAutoMapper
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initializing the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Students, StudentsDTO>()
                );

            //Instanciating the source
            Students st = new Students
            {
                FirstName
 = "Rajkishore",
                LastName
 = "Sahoo"
              
            };

            //Use automapper
            var mapper = new Mapper(config);
            var stDTO = mapper.Map<StudentsDTO>(st);
            //OR
            //var stDTO2 = mapper.Map<Students, StudentsDTO>(st);

            Console.WriteLine("FirstName:" + stDTO.FirstName + ", LatName:" + stDTO.Salary);
            Console.ReadLine();
        }
    }
    
    public class Students
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
    }

    public class StudentsDTO
    {
        public string FName { get; set; }
        public string LastName { get; set; }
    }
}

How to use projections in AutoMapper?

When we are discussing the Projections here, that means when the structure of the source is different than the structure of the destination. No worries. Automapper has great support for this scenario. Let’s see an example of the implementation.

public class EmployeeAddress
    {
        public string State { get; set; }
        public string Country { get; set; }
    }

The Employee class looks like below.

public class Employee
    {
        public int EmpId
        {
            get; set;
        }
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
        public EmployeeAddress EmployeeAddress

        {
            get; set;
        }
    }

The EmployeeDTO class looks like the below

public class Employee
    {
        public int EmpId
        {
            get; set;
        }
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
       public string State { get; set; }
       public string Country { get; set; }
    }

The implementation of the automapper will be like below

var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<EmployeeDTO, Employee>()
                   .ForMember(destination => destination.EmployeeAddress,
              map => map.MapFrom(
                  source => new EmployeeAddress
                  {
                      State = source .State,
                      Country = source.Country
                  }));

This how you can impliment projections in AutoMapper using C#.

Best Practices AutoMapper

Below are a few best practices that are recommended

  1. It is better to avoid calling the CreateMap() on each request if possible. Do it once in the StartUp class.
  2. Try avoiding the inline mappings wherever possible.
  3. If the mapping is complex, it is better not to use the automapper feature.

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