.NET Core

Create Microservices Using ASP.NET Core

In this article, we’re creating a microservice using asp.net core. Microservices is a software development style that arose from current trends to establish techniques that aim to improve the speed and efficiency of developing and managing large-scale software solutions. Microservices are more about using a set of concepts and architectural patterns to build a system. Each microservice is self-contained, but they are all dependent on one another. All microservices in a project are separately deployed in production, on-premise or in the cloud, and live side by side.

Creating an ASP.NET Core Application

  1. Add a new project to the Visual Studio.

2. Choose ASP.NET Core Web Application as the application type and give it a suitable name.

3. Next, choose the 3.1 .NET Framework as the type of the project.

First Add Models

– Create a new folder called “Models.”, In the Models folder, add a class named Product and Category.

  • Product Model
public class Product
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public decimal Price { get; set; }

    public int CategoryId { get; set; }
}
  • Category Model
public class Category
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
}

Add Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore should be the package inside the downloaded SDKs.

Add a new DBConext Folder, in this folder add DatabaseContext.cs

public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Category>().HasData(
            new Category
            {
                Id = 1,
                Name = "Television",
                Description = "Electronic Items",
            },
            new Category
            {
                Id = 2,
                Name = "Clothes",
                Description = "Dresses",
            },
            new Category
            {
                Id = 3,
                Name = "Food",
                Description = "Grocery Items",
            }
        );
    }
}

Add a connection string in the appsettings.json file.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DBConnection": "Server=SERVER_NAME;Database=DATABASE_NAME;User Id=USERNAME;Password=PASSWORD;Connect Timeout=120;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  }
}

To add the SQL server database provider for EF Core, open the Startup. cs file. Add the code services to the mix.

string connectionString = Configuration.GetConnectionString("DBConnection");
 services.AddDbContext<DatabaseContext>(options =>
                options.UseSqlServer(connectionString)
               .UseLazyLoadingProxies());

It’s worth noting that the GetConnectionString method accepts the name of the connection string’s key, which was specified in the appsettings file.

Now we can Repository,

The repository is a micro component of a microservice that encapsulates the data access layer while also assisting with data persistence and testability.

In the project, create a new folder called Repository and a new interface called IProductRepository in that folder. In the Product microservice interface, add the methods that conduct CRUD operations.

IProductRepository.cs

public interface IProductRepository
{
    IEnumerable<Product> GetProducts();

    Product GetProductById(int Id);

    Int32 InsertProduct(Product product);

    bool UpdateProduct(Product product);

    bool DeleteProduct(int Id);

    void Save();
}

ProductRepository.cs

public class ProductRepository : IProductRepository
{
    private readonly DatabaseContext _dbContext;

    public ProductRepository(DatabaseContext dbContext)
    {
        _dbContext = dbContext;
    }
  

    public Product GetProductById(int productId)
    {
        return _dbContext.Products.Find(productId);
    }

    public IEnumerable<Product> GetProducts()
    {
        return _dbContext.Products.ToList();
    }

    public Int32 InsertProduct(Product product)
    {
        Int32 response = 0;
        try
        {
            _dbContext.Add(product);
            Save();
            response = product.Id;
        }
        catch (Exception ex)
        {
            response = 0;
        }
        return response;
    }

    public bool UpdateProduct(Product product)
    {
        bool response = false;
        try
        {
            _dbContext.Entry(product).State = EntityState.Modified;
            Save();
            response = true;
        }
        catch(Exception ex)
        {
            response = false;
        }
        return response;
    }

    public bool DeleteProduct(int productId)
    {
        bool response = false;
        try
        {
            var product = _dbContext.Products.Find(productId);
            _dbContext.Products.Remove(product);
            Save();

           response = true;
        }
        catch (Exception ex)
        {
            response = false;
        }

        return response;
    }

    public void Save()
    {
        _dbContext.SaveChanges();
    }


}

In the project, open the Startup class and add the code as services. Inside the ConfigureServices method, call services.AddTransient<IProductRepository, ProductRepository>(); to resolve the repository’s dependency at runtime.

Add Controller 

The microservice should have an endpoint, which necessitates the use of a controller that exposes the HTTP methods to the client as service method endpoints.

Add a new Controller by right-clicking on the Controllers folder, as illustrated below and Give the name of the controller as ProductController.

Call the repository methods to add implementation to the methods, as demonstrated below. The most simple implementation is presented here to help you grasp the concept. The methods might be attribute routed, and more annotations could be added as needed.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProductService.Models;
using ProductService.Repository;
using System.Transactions;

namespace ProductService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IProductRepository _productRepository;

        public ProductController(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        [HttpGet]
        public IActionResult Get()
        {
            var products = _productRepository.GetProducts();
            return new OkObjectResult(products);
        }

        [HttpGet("{id}", Name = "Get")]
        public IActionResult Get(int id)
        {
            var product = _productRepository.GetProductById(id);
            return new OkObjectResult(product);
        }

        [HttpPost]
        public IActionResult Post([FromBody] Product product)
        {
            using (var scope = new TransactionScope())
            {
                _productRepository.InsertProduct(product);
                scope.Complete();
                return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
            }
        }

        [HttpPut]
        public IActionResult Put([FromBody] Product product)
        {
            if (product != null)
            {
                using (var scope = new TransactionScope())
                {
                    _productRepository.UpdateProduct(product);
                    scope.Complete();
                    return new OkResult();
                }
            }
            return new NoContentResult();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            _productRepository.DeleteProduct(id);
            return new OkResult();
        }
    }
}

After that, you can migrations the database context file.

We can use migrations to offer code that will change the database from one version to the next.

  1. Open Package Manager Console.
  2. To activate the migration, type Add-Migration and a sensible name, such as InitialCreate, before pressing enter.
  3. If we look at our solution now after the command is run, we can notice a new Migrations folder. It also comes with two files. First, let’s take a look at our present context model. Please feel free to look through the files. The files themselves are quite self-explanatory.
  4. Another command is used to guarantee that migrations are done to the database. It’s referred to as the update database. The migrations will be applied to the current database if they are run.
  5. When viewing the data in the Categories table, the default master data for three categories are displayed

Now Run the MicroService and you can perform CRUD operation in the postman.

After the successfully tested in Local. you can live this service. and Run into another project for the Product section.

Conclusion

A microservice is a bounded context service that is developed around a specific business capability and can be deployed separately. This article on microservices explained what they are and how they differ from monolithic service design. The article explains how to create a microservice using ASP.NET Core and deploy it using IIS. Similarly, the service can contain several pictures and run on multiple containers at the same time.

I hope you can see how I can accomplish this. Let me know if you face any difficulties.

You can watch my previous blog here.

Happy Coding {;}

 

 

 

 

 

 

 

 

 

Nayan Raval

Nayan Raval is a MEAN Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. Key Areas Of Expertise: • ASP.NET Core MVC • ASP.NET Core Web API • C# • ASP.NET MVC 5 • Angular All versions • HTML5 • CSS3 / SCSS • Bootstrap • JavaScript • Azure • JQuery Databases and related • Microsoft SQL server MSSQL • PostgreSQL • Entity Framework (EF) • LINQ UI Frameworks • Kendo UI • Telerik • JQuery UI • Prime NG and Material UI API Integration • SignalR • DateDog • Twilio Voice Call And Message • Stripe • SendGrid (Email Camping) • Checkr • Zoom Video Call • Auth0 • Elastic Search • Quartz - Scheduler • JWT Token • Google Calendar

View Comments

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago