Creating A C# Microservice And Deploying It To Azure

Introduction

In the previous article, I talked about microservices and their advantages. In today’s article, we will look into creating a C# microservice and then deploying it to Azure as an App service. We will create the Employee microservice. This will be a Web API solution and it will be tested using Postman So, let us begin.

Creating the C# microservice

Create a new Web API project in Visual Studio 2022 community preview edition.

Creating A C# Microservice And Deploying It To Azure

Creating A C# Microservice And Deploying It To Azure

Creating A C# Microservice And Deploying It To Azure

Creating A C# Microservice And Deploying It To Azure

Creating A C# Microservice And Deploying It To Azure

Run the solution to ensure all works fine.

Creating A C# Microservice And Deploying It To Azure

Next, add three-class library projects as below,

  1. Employee.Common (for common classes and interfaces)
  2. Employee.DAL (for the data access layer – set a project reference to Employee.Common)
  3. Employee.BL (for the business logic layer – set a project reference to Employee.Common)

Also, set a project reference for all projects in the Employee.WebAPI project.

Creating A C# Microservice And Deploying It To Azure

We now start to update the code.

For Employee.Common, setup is as below,

Creating A C# Microservice And Deploying It To Azure

Then add, the below code,

using System.Collections.Generic;
namespace Employee.Common.PublicInterfaces {
    public interface IDepartmentBL {
        List < Department > GetAllDepartments {
            get;
        }
    }
}
using System.Collections.Generic;
namespace Employee.Common.PublicInterfaces {
    public interface IDepartmentDao {
        List < Department > GetAllDepartments {
            get;
        }
    }
}
using System.Collections.Generic;
namespace Employee.Common.PublicInterfaces {
    public interface IEmployeeBL {
        List < Common.Employee > GetEmployeesByDepartment(int departmentId);
        Common.Employee ? GetEmployeesById(int employeeId);
    }
}
using System.Collections.Generic;
namespace Employee.Common.PublicInterfaces {
    public interface IEmployeeDao {
        List < Common.Employee > GetEmployeesByDepartment(int departmentId);
        Common.Employee ? GetEmployeesById(int employeeId);
    }
}
namespace Employee.Common {
    public class Department {
        public int Id {
            get;
            set;
        }
        public string Name {
            get;
            set;
        }
    }
}
namespace Employee.Common {
    public class Employee {
        public int Id {
            get;
            set;
        }
        public string Name {
            get;
            set;
        }
        public string Address {
            get;
            set;
        }
        public string Phone {
            get;
            set;
        }
        public string EmailAddress {
            get;
            set;
        }
        public int DepartmentId {
            get;
            set;
        }
    }
}

For Employee.DAL, setup as below,

Creating A C# Microservice And Deploying It To Azure

Then add, the below code (Note we are using hardcoded data. In a real-life application we would probably get the data from a data store),

using Employee.Common;
using Employee.Common.PublicInterfaces;
using System.Collections.Generic;
namespace Employee.DAL {
    public class DepartmentDao: IDepartmentDao {
        List < Department > _departments;
        public DepartmentDao() {
            _departments = new List < Department > () {
                new Department {
                    Id = 1, Name = "Finance"
                }, new Department {
                    Id = 2, Name = "Marketing"
                }
            };
        }
        public List < Department > GetAllDepartments => _departments;
    }
}
using Employee.Common.PublicInterfaces;
using System.Collections.Generic;
using System.Linq;
namespace Employee.DAL {
    public class EmployeeDao: IEmployeeDao {
        List < Common.Employee > _employees;
        public EmployeeDao() {
            _employees = new List < Common.Employee > () {
                new Common.Employee {
                        Id = 1, Name = "John Doe", Address = "Toronto, ON", Phone = "12345", EmailAddress = "a@a.com", DepartmentId = 1
                    },
                    new Common.Employee {
                        Id = 2, Name = "Jane Doe", Address = "Etobicoke, ON", Phone = "7891011", EmailAddress = "b@a.com", DepartmentId = 2
                    },
                    new Common.Employee {
                        Id = 3, Name = "Mary Smith", Address = "Mississauga, ON", Phone = "22556644", EmailAddress = "c@a.com", DepartmentId = 2
                    }
            };
        }
        public List < Common.Employee > GetEmployeesByDepartment(int departmentId) {
            return _employees.Where(e => e.DepartmentId == departmentId).ToList();
        }
        Common.Employee ? IEmployeeDao.GetEmployeesById(int employeeId) {
            return _employees.FirstOrDefault(e => e.Id == employeeId);
        }
    }
}

For Employee.BL, setup as below,

Creating A C# Microservice And Deploying It To Azure

Then add, the below code,

using Employee.Common;
using System.Collections.Generic;
using Employee.Common.PublicInterfaces;
namespace Employee.BL {
    public class DepartmentBL: IDepartmentBL {
        private readonly IDepartmentDao _departmentDao;
        public DepartmentBL(IDepartmentDao departmentDao) {
            _departmentDao = departmentDao;
        }
        public List < Department > GetAllDepartments => _departmentDao.GetAllDepartments;
    }
}
using Employee.Common.PublicInterfaces;
using System.Collections.Generic;
namespace Employee.BL {
    public class EmployeeBL: IEmployeeBL {
        private readonly IEmployeeDao _employeeDao;
        public EmployeeBL(IEmployeeDao employeeDao) {
            _employeeDao = employeeDao;
        }
        public List < Common.Employee > GetEmployeesByDepartment(int departmentId) {
            return _employeeDao.GetEmployeesByDepartment(departmentId);
        }
        public Common.Employee ? GetEmployeesById(int employeeId) {
            return _employeeDao.GetEmployeesById(employeeId);
        }
    }
}

And finally, setup the Employee.WebAPI project as below,

Creating A C# Microservice And Deploying It To Azure

And update the code as below,

using Employee.Common;
using Employee.Common.PublicInterfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
namespace Employee.WebAPI.Controllers {
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController: ControllerBase {
        private readonly ILogger < DepartmentController > _logger;
        private readonly IDepartmentBL _departmentBL;
        public DepartmentController(ILogger < DepartmentController > logger, IDepartmentBL departmentBL) {
                _logger = logger;
                _departmentBL = departmentBL;
            }
            [HttpGet]
        public IEnumerable < Department > Get() {
            return _departmentBL.GetAllDepartments;
        }
    }
}
using Employee.Common.PublicInterfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
namespace Employee.WebAPI.Controllers {
    [ApiController]
    public class EmployeeController: ControllerBase {
        private readonly ILogger < EmployeeController > _logger;
        private readonly IEmployeeBL _employeeBL;
        public EmployeeController(ILogger < EmployeeController > logger, IEmployeeBL employeeBL) {
                _logger = logger;
                _employeeBL = employeeBL;
            }
            [HttpGet]
            [Route("api/[controller]/departments")]
        public IEnumerable < Common.Employee > Get(int departmentId) {
                return _employeeBL.GetEmployeesByDepartment(departmentId);
            }
            [HttpGet]
            [Route("api/[controller]/details")]
        public Common.Employee GetEmployee(int employeeId) {
            return _employeeBL.GetEmployeesById(employeeId);
        }
    }
}
using Employee.BL;
using Employee.Common.PublicInterfaces;
using Employee.DAL;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped < IDepartmentDao, DepartmentDao > ();
builder.Services.AddScoped < IEmployeeDao, EmployeeDao > ();
builder.Services.AddScoped < IDepartmentBL, DepartmentBL > ();
builder.Services.AddScoped < IEmployeeBL, EmployeeBL > ();
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c => {
    c.SwaggerDoc("v1", new() {
        Title = "Employee.WebAPI", Version = "v1"
    });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment()) {
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee.WebAPI v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

We now run the application locally and see the below,

Creating A C# Microservice And Deploying It To Azure

We can also test our endpoints from Postman as below,

Creating A C# Microservice And Deploying It To Azure

Creating A C# Microservice And Deploying It To Azure

Creating A C# Microservice And Deploying It To Azure

We are now ready to deploy the Web APIs to Azure.

Deploying the microservice to Azure

We create an App Service in Azure as below,

Creating A C# Microservice And Deploying It To Azure

We then publish the code from Visual Studio.

Creating A C# Microservice And Deploying It To Azure

Creating A C# Microservice And Deploying It To Azure

Creating A C# Microservice And Deploying It To Azure

Once published, we can test our Web APIs using postman as below,

Creating A C# Microservice And Deploying It To Azure

Summary

In this article, we took a look at creating a microservice Web API in C# and deploying it to Azure. We can scale this application as required without impacting any other microservice and changes to it will not affect any other service as long as the public interfaces stay the same. This design architecture adds a lot of flexibility to our overall system design. Happy coding!