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
  • 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 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
automapper azure functions

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

Install-Package AutoMapper
automapper dependency injection
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

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.

Automapper Tutorial

The automapper is basically is a mapping or mapper between two objects or you can consider it as an object-object mapper. It is an excellent feature that actually 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 that provides 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 dynamically get the type of object from an existing object and that helps to easily access its properties.

How do I use AutoMapper C#?

In order 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 say 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 are same while using the Automapper.

Another good thing is Auto mapper will ignore the null reference exceptions during the time 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 in order to use the automapper feature in your application. You can easily able to 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 down here is, 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 will consider the Students and StudentsDTO class, the syntax will be like 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 we have already discussed above, you should do the automapper configuration once per app domain so you should keep the automapper configuration code in the startup class. For example, if you will 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 is different than 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 when the name of the properties in the source are different than the property name in the destination is by using the .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;
        }
    }

Here in this example, if you can see the first property name in the Students(Source) class is FirstName and in the StudentsDTO(Destination) class is FName. If we will have to implement the automapper feature in this scenario, then 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 on 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 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 few best practices that are recommanded

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

Ilogger Azure Functions

While working with the Azure function, sometimes there might be a chance that you will get some errors, warnings, critical issues from the code. Now, if you want to tract those issues meaning if you are interested to know what and where exactly the problem is, then the ILogger interface is the right choice in this scenario, you can log the details into a log file.

When you will be logging the details into a log file, in case of any issues, you will come to know about that by analyzing the log file that will provide enough information on the root cause of the issue. You will also able to identify which is the exact function or exact place, where the issue is actually occurring.

Basically, logging is one of the essential components for your Azure function to analyze the behavior and useful when you need to troubleshoot in case of any issues.

Ilogger is the alternative for TraceWriter that was there before. The TraceWriter is obsolete with Azure Functions version 2.0.

One more benefit with ilogger is, it supports structured logging. It supports the below types of logging.

  • Info (LogInformation)
  • Debug (LogDebug)
  • Error (LogError)
  • Warning (LogWarning)
  • Critical (LogCritical)
  • Trace (LogTrace)

Below is an example of the implementation of Ilogger.

namespace AzureFunctionSQL
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            using (var con1 = new SqlConnection("Server=tcp:sql1246.database.windows.net,1433;Initial Catalog=MySQLDB;Persist Security Info=False;User ID=Rajkishore;[email protected];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))

            {
                try
                {
                    SqlCommand command1 = new SqlCommand();
                    command1.CommandText = "INSERT INTO Customers(customerID, LastName, FirstName) VALUES (15, 'SaiRam', 'SaiRam')";
                    //command1.CommandType = CommandType.StoredProcedure;
                    command1.Connection = con1;
                    con1.Open();
                    command1.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    log.LogInformation(ex.Message);

                }

            }

        }
    }

Azure Function ilogger Dependency Injection

You can use the ilogger interface in your startup class. You need to use the “LoggerFactory” class to create the instance for the ilogger interface.

public class Startup: FunctionsStartup {  
    private ILoggerFactory _loggerFactory;  
    public override void Configure(IFunctionsHostBuilder builder) {  
        var myconfig = new ConfigurationBuilder().AddJsonFile("local.settings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();  
        builder.Services.AddLogging();  
        ConfigureServices(builder);  
    }  
    public void ConfigureServices(IFunctionsHostBuilder builder) {  
        _loggerFactory = new LoggerFactory();  
        var logger = _loggerFactory.CreateLogger("Startup");  
        logger.LogInformation("I am in Startup");  
        //builder implementation goes here 
    }  
}  

Azure Functions V3 Configuration

You can check out the details on Azure Functions V3 Configuration now.

Dependency Injection Azure Functions

Find out a complete tutorial on Dependency Injection Azure Functions now.

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, 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?, 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, Ilogger Azure Functions, Azure Function ilogger Dependency Injection, Azure Functions V3 Configuration, Dependency Injection Azure Functions. Hope you have enjoyed this Article !!!