Saturday, 21 September 2024

EF Core Migrations

What is EF Core Migrations

In EF core we create or update data models in our code. We call this approach the Code First approach. As our app grows, we are going to make a lot of changes to our model. This will result in our database going out of sync with the model.

Hence we need to update the database as we make changes to the model. But making changes manually is error-prone. We can also create a fresh database from the model, but it will result in loss of data.

The EF Core migrations make it easier to push the changes to the database and also preserve the existing data in the database. It provides commands like add-migration, remove-migration to create & remove migrations. Once migrations are generated, we update the database using the update-database. We can also generate the migration script and execute it in the production server.

How to Create Ef Core Migrations

Let us create a new console application to see how migrations work in entity framework core. Name the app as EFCoreMigration.

First, We will create a model and context class. Then we use the Migrations commands to create migrations and then later update the database.

Install the Microsof.Entity FrameworkCore.SqlServer package, which in turn installs the Entity Framework Core package

Install-package Microsoft.EntityFrameworkCore.SqlServer

Models for Migration

Create the Models folder and create two class Product.cs and Vendor.cs as shown below

Context: Under the models folder create the context class EFContext, which inherits from DBContext as shown below

using Microsoft.EntityFrameworkCore;
 
namespace EFCoreMigration.Models
{
    public class EFContext : DbContext
    {
 
        private const string connectionString = "Server=(localdb)\\mssqllocaldb;Database=EFCoreMigration;Trusted_Connection=True;";
 
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(connectionString);
        }
 
        public DbSet<Product> Products { get; set; }
        public DbSet<Vendor> Vendors { get; set; }
    }
}

Preparing for Migration

Open the Package Manager and run the following command.

Install-Package Microsoft.EntityFrameworkCore.Tools

Installing the above package also installs the Microsoft.EntityFrameworkCore.Design package. This package actually contains the commands like add migrations, Update database, scaffold an existing database by reverse-engineering the schema of a database, etc

List of Migration Commands

add migration

Whenever you create or Modify the domain classes, then the first thing you need to do is to create a Migration. This is done by add-migration command (or by using dotnet EF migrations add command line)

Open the Package Console manager and run the command

add-migration "initial" 

Inspecting the Migration scripts

The add-migration command created three classes under the folder Migrations. One is the Migration class and the second one is the designer class & the last one is snapshot class.

The add-migration command generates this file when it is run for the first time. In the subsequent runs, it uses it to find out the changes to be made to the model. It then overwrites it so that it remains up to date.

Update database

The add-migration creates the migration package but does not create the database.

The update-database command is used to bring the database in sync with the latest migration or the migration name specified as the argument

Run the update-database as shown below

update-database  

Open the SQL Server and you will see that the tables Products & vendors are created in the Database. Also, note that the _EFMigrationsHistory table.

__EFMigrationsHistory

This table keeps track of the Migrations applied to the database. It contains two columns one is MigrationId and ProductVersion. MigrationId contains the Unique ID of the migration and ProductVersion is the version number of Entity Framework used.

The update-databasechecks if the database exists. If the table __EFMigrationsHistory does not exists then the update-database applies the migration from the beginning and then creates the __EFMigrationsHistory

If __EFMigrationsHistory already exists, then update-database checks the to see the last migration applied and then continues to apply the migrations from the last migrations to the latest. It then inserts latest migration id in the __EFMigrationsHistory table

Update-database never checks the database schema to verify whether it matches with the model. So if you accidentally delete the __EFMigrationsHistory table, alter or delete any other table or fields, the EF Core never reports an error. The error occurs only when the App is running and you query the altered/deleted table

Connection string for update-database

The update-database requires us to create the OnConfiguring() method in the context class and expects us to pass the correct connection string to the desired database provider. For example if you are using the Sql Server then you need to call the method UseSqlServer(ConnectionString)

That is because the update-database instantiates the Context class and executes the onConfiguring method so as to configure the context. It is unaware of how and where you have stored the connection string. And it does not have the access to Dependency injection container as it runs outside the project.

Reference: https://www.tektutorialshub.com/


Continue Reading →

@Self, @SkipSelf & @Optional Decorators Angular

@Self, @SkipSelf and @Optional are Angular Decorators that configure how the DI Framework should resolve the dependencies. These decorators are called Resolution Modifiers because they modify the behavior of injectors. In this page, we will learn @Self, @SkipSelf, & @Optional. 

 How Angular DI Framework Resolves Dependencies

When a component asks for Dependency, the DI Framework resolves it in two phases.

In the first phase, it starts to look for the Dependency in the current component’s ElementInjector. If it does not provide the Dependency, it will look in the Parent Components ElementInjector. The Request bubbles up until it finds an injector that provides the service or reaches the root ElementInjector.

If ElementInjector does not satisfy the request, Angular looks for the Dependency in the ModuleInjector hierarchy. If Angular still doesn’t find the provider, it throws an error.

We have created an example project in Angular to explain the @Self, @SkipSelf, & @Optional. 

The Code contains a RandomService, which generates a Random Number when initialized. The Angular Service is added to the Providers array of the AppModule. We can inject this service anywhere in our Application.

@Injectable({
  providedIn: "root"
})
export class RandomService {

The project contains three Angular Components (AppComponent, ChildComponent & GrandChildComponent) all inject the RandomService and displays the Random Number from the Service.

We also have testDirective, which we include in the template of GrandChildComponent. It also displays the Random Number from the Service.

Ensure that the Providers array is empty in all components & directives. Run the App. Angular creates only one instance of the RandomService. That is why all the components and directives show the same number.


@Self: The @Self decorator instructs Angular to look for the dependency only in the local injector. The local injector is the injector that is part of the current component or directive.

import { Component, SkipSelf, Self, Optional, Host } from "@angular/core";
import { RandomService } from "./random-service";

@Component({
  selector: "my-grandChild",
  template: `
    <div class="box">
      GrandChildComponent => {{ randomNo }}
      <div class="dirbox" testDirective>fdf</div>
    </div>
  `,
  providers: [RandomService]
})
export class GrandChildComponent {
  randomNo;
  constructor(@Self() private randomService: RandomService) {
    this.randomNo = randomService.RandomNo;
  }

This forces the Angular DI Framework to look for the Dependency attached to the current Component. I added the RandomService to the providers array of the GrandChildComponent.

As you can see from the image Angular creates two instances of RandomService. One from the AppModule and another from the GrandChildComponent. Also, note that testDirective picks up the RandomService provided from the GrandChildComponent and not from the AppModule

@SkipSelf: The @SkipSelf decorator instructs Angular to look for the dependency in the Parent Injector and upwards.

It tells Angular not to look for the injector in the local injector, but start from the Parent. You can think of this decorator as the opposite of the @Self

Open the GrandChildComponent again. Add the SkipSelf instead of Self decorator.

export class GrandChildComponent {
  randomNo;
  constructor(@SkipSelf() private randomService: RandomService) {
    this.randomNo = randomService.RandomNo;
  }
}

As you can see from the image, the GrandChildComponent, picks up RandomService instance provided by the Module and not the one provided by itself. 
But, the testDirective still picks up the RandomService provided by the GrandChildComponent.

@Optional: Optional marks the dependency as Optional. If the dependency is not found, then it returns null instead of throwing an error

In the GrandChildComponent remove the RandomService from the Providers Array and add the @Self decorator. You will instantly receive the error “No provider for RandomService found in NodeInjector“.

Add the @Optional decorator along with the @Self. Now, the dependency injection will return null instead of an error.

Also, remember to add the ? in randomService?, else you will get the “Cannot read property ‘RandomNo’ of null” error.

export class GrandChildComponent {
  randomNo;
  constructor(@Optional() @Self() private randomService: RandomService) {
    this.randomNo = randomService?.RandomNo;
  }
}

As you can see in the image, GrandChildComponent does not receive any values, while testDirective picks up the RandomService provided by the AppModule



Continue Reading →

Saturday, 17 August 2024

Entity Framework Core

Entity Framework Core (EF Core) is an open-source, lightweight, and extensible Object-Relational Mapper (ORM) developed by Microsoft. It is designed to work with .NET applications to facilitate data access and manipulation using object-oriented programming concepts.

Here are some key features and concepts of EF Core:

  1. Object-Relational Mapping (ORM): EF Core helps in mapping .NET objects to database tables, allowing developers to interact with a database using strongly-typed C# classes rather than writing raw SQL queries.

  2. Database Providers: EF Core supports a variety of database systems through different database providers, including Microsoft SQL Server, SQLite, PostgreSQL, MySQL, and more. Each provider contains the necessary implementation for working with a specific type of database.

  3. LINQ Queries: EF Core allows developers to write queries using Language Integrated Query (LINQ), which is then translated into the appropriate SQL queries by the framework.

  4. Migrations: EF Core provides a migrations feature that helps manage database schema changes over time. It allows developers to create, modify, and update database schemas in a controlled manner.

  5. Change Tracking: EF Core tracks changes made to entities and automatically generates the necessary SQL commands to update the database when SaveChanges is called.

  6. Caching and Performance: EF Core includes various performance optimization features, such as caching and lazy loading, to improve the efficiency of data access operations.

  7. NoSQL Support: Although EF Core is primarily used with relational databases, it also has some support for NoSQL databases, particularly through custom providers and extensions.

  8. Cross-Platform: EF Core is cross-platform and can be used with .NET Core, making it suitable for developing applications that run on different operating systems, including Windows, Linux, and macOS.

Difference between entity framework and entity framework core : Click here

EF Core is part of the larger .NET ecosystem and is commonly used in ASP.NET Core applications to handle data access. It provides a high-level, abstracted way to interact with databases, allowing developers to focus more on business logic rather than database-related concerns.

EF Core Database First Approach
Sometimes we may have an existing database. When we have a database and the database tables already, we use the database first approach. With the database first approach, EF Core creates the DBContext and Domain classes based on the existing database schema.

EF Core Database Providers
EF Core supports many relational and even non relational databases. EF Core is able to do this by using plug-in libraries called the database providers. These database providers are available as NuGet packages. 

List of EF Core Database Providers

https://docs.microsoft.com/en-us/ef/core/providers/

A database provider, usually sits between EF Core and the database it supports. The database provider contains the functionality specific to the database it supports. Functionality that is common to all the databases is in the EF Core component. Functionality that is specific to a database, for example, Microsoft SQL Server specific functionality is with-in the SQL Server provider for EF Core. 

To install Entity Framework Core and to be able to use SQL server as the database for your application, you need to install the following nuget packages.

Microsoft.EntityFrameworkCore.SqlServer - This nuget package contains SQL Server specific functionality

Microsoft.EntityFrameworkCore.Relational - This nuget package contains functionality that is common to all relational databases

Microsoft.EntityFrameworkCore - This nuget package contains common entity frameowrk core functionality

When we install Microsoft.EntityFrameworkCore.SqlServer package, it also installs all the other dependant nuget packages automatically. 

DbContext in entity framework core

One of the very important classes in Entity Framework Core is the DbContext class. This is the class that we use in our application code to interact with the underlying database. It is this class that manages the database connection and is used to retrieve and save data in the database.

To use the DbContext class in our application We create a class that derives from the DbContext class.
DbContext class is in Microsoft.EntityFrameworkCore namespace.

public class AppDbContext : DbContext
{ }


For the DbContext class to be able to do any useful work, it needs an instance of the DbContextOptions class.
 The DbContextOptions instance carries configuration information such as the connection string, database provider to use etc.
To pass the DbContextOptions instance we use the constructor as shown in the example below.

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions[AppDbContext] options)
        : base(options)
    {
    }
    public DbSet[Employee] Employees { get; set; }
}


The DbContext class includes a DbSet[TEntity] property for each entity in the model.

Using sql server with entity framework core
When using Entity Framework Core, one of the important things that we need to configure is the database provider that we plan to use.  Click here

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool[AppDbContext](options =>
      options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

    services.AddMvc().AddXmlSerializerFormatters();
    services.AddTransient[IEmployeeRepository, MockEmployeeRepository]();
}


We want to configure and use Microsoft SQL Server with entity framework core. We usually specify this configuration in ConfigureServices() method in Startup.cs file.

We can use either AddDbContext() or AddDbContextPool() method to register our application specific DbContext class with the ASP.NET Core dependency injection system.

The difference between AddDbContext() and AddDbContextPool() methods is, AddDbContextPool() method provides DbContext pooling.

With DbContext pooling, an instance from the DbContext pool is provided if available, rather than creating a new instance.

DbContext pooling is conceptually similar to how connection pooling works in ADO.NET.

From a performance standpoint AddDbContextPool() method is better over AddDbContext() method.

UseSqlServer() extension method is used to configure our application specific DbContext class to use Microsoft SQL Server as the database.

To connect to a database, we need the database connection string which is provided as a parameter to UseSqlServer() extension method

Instead of hard-coding the connection string in application code, we store it appsettings.json configuration file.

{
    "ConnectionStrings": {
      "EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;
Trusted_Connection=true"
    }
  }


To read connection string from appsettings.json file we use IConfiguration service GetConnectionString() method.

Entity framework core migrations- Click here, Click here, Click here

Migration is an entity framework core feature that keeps the database schema and our application model classes (also called entity class) in sync.

If you have not executed at-least the initial migration in your application you might get the following SqlException

SqlException: Cannot open database "EmployeeDB" requested by the login.

This is because we do not have the database created yet. One way to create the database is by 

  • Creating a migration first and then
  • Executing that migration

We will be using the following commands to work with migrations in entity framework core.

Add-Migration: Adds a new migration
Update-Database: Updates the database to a specified migration
Remove-Migration: It only removes one migration at a time and that too only the latest migration that is not yet applied to the database. If all the migrations are already applied, executing Remove-Migration command throws the following exception.

Creating a Migration in Entity Framework Core
The following command creates the initial migration. InitialCreate is the name of the migration.

Add-Migration InitialCreate


When the above command completes, you will see a file in the "Migrations" folder that contains the name InitialCreate.cs. This file has the code required to create the respective database tables.

Update-Database in Entity Framework Core
We need to execute the migration code to create the tables. If the database does not exist already, it creates the database and then the database tables. For updating the database, we use Update-Database command. To the Update-Database command we may pass the migration name we want to execute. If no migration is specified, the command by default executes the last migration.

Entity framework core seed data Click here
If you are using Entity Framework Core 2.1 or later there is a new method of seeding database data. In your application DbContext class, override OnModelCreating() method.

HasData() method configures entity to have the specified seed data.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity[Employee]().HasData(
        new Employee
        {
            Id = 1,
            Name = "Mark",
            Department = Dept.IT,
            Email = "mark@pragimtech.com"
        }
    );
}


EF CORE Simple project https://www.tektutorialshub.com/

Continue Reading →

Saturday, 11 November 2023

CQRS pattern

CQRS, or Command Query Responsibility Segregation, is a design pattern that separates the responsibilities of reading and writing data in a software system. Here’s a breakdown of its key concepts:

Key Concepts

  1. Separation of Concerns:

    • Commands: These are actions that change the state of the system (e.g., creating, updating, or deleting data). They do not return data.
    • Queries: These are operations that retrieve data without altering the system’s state. They are designed for read operations.

Here's a simple example of implementing the CQRS pattern in C#:

 // Command
public class CreateProductCommand
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Command Handler
public class CreateProductCommandHandler
{
    public void Handle(CreateProductCommand command)
    {
        // Logic to create a new product and update the state
        // This might involve validation, persistence, and other business logic

        Console.WriteLine($"Product '{command.Name}' created successfully with price {command.Price}");
    }
}

// Query
public class GetProductQuery
{
    public int ProductId { get; set; }
}

// Query Handler
public class GetProductQueryHandler
{
    public Product Handle(GetProductQuery query)
    {
        // Logic to retrieve product information from the state
        // This might involve querying a database, caching, or other mechanisms

        return new Product
        {
            ProductId = query.ProductId,
            Name = "Sample Product",
            Price = 29.99m
        };
    }
}

// Model
public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Example Usage
class Program
{
    static void Main()
    {
        // Command side usage
        var createProductCommand = new CreateProductCommand
        {
            Name = "Example Product",
            Price = 49.99m
        };

        var createProductHandler = new CreateProductCommandHandler();
        createProductHandler.Handle(createProductCommand);

        // Query side usage
        var getProductQuery = new GetProductQuery
        {
            ProductId = 1
        };

        var getProductHandler = new GetProductQueryHandler();
        var product = getProductHandler.Handle(getProductQuery);

        Console.WriteLine($"Product Name: {product.Name}, Price: {product.Price}");
    }
}

In this example, the CreateProductCommand represents a command for creating a new product, and the CreateProductCommandHandler handles this command, updating the system state accordingly. On the query side, the GetProductQuery represents a query to retrieve product information, and the GetProductQueryHandler handles this query, providing the necessary data from the system state. The Product class is a simple model representing a product.

Benefits:

  • Scalability: By separating reads and writes, you can optimize each side independently. For instance, you might use different data stores or caching mechanisms for reading.
  • Performance: Read and write models can be tailored for their specific tasks, potentially improving performance.
  • Flexibility: Allows for different data models for reads and writes, which can simplify complex domains.

Reference: https://www.c-sharpcorner.com


Continue Reading →

MicroService Interview Q/A

What is a Microservice?

Microservices are an architectural style that involves breaking down a large application into a collection of loosely coupled services that communicate over well-defined APIs. Each microservice is designed to perform a specific business function and can be developed, deployed, and scaled independently.

What are the key characteristics of Microservices?

  1. Loose Coupling : Microservices operate independently of each other. It can be developed, deployed, and scaled independently.
  2. Single Responsibility Principle: Each service should have a single responsibility and focus on a specific business capability.
  3. Resilience: Failure in one service does not affect others.
  4. Scalability: Each service can be scaled independently.
  5. Decentralized Data Management: Each service manages its own database.

How do Microservices communicate with each other?

Microservices commonly communicate through lightweight protocols such as HTTP/REST, or message queues like RabbitMQ or Apache Kafka.

What is the difference between Microservices and Monolithic architecture?

In a monolithic architecture, all components of the software are tightly linked and run as a single service. This means that any changes made to even a small part of the application could affect the whole system.

In contrast, microservices architecture breaks down the application into smaller, independent services that run their own processes and communicate via well-defined APIs. This independence allows for easier scaling, more resilience, and faster deployment cycles.

Explain the concept of Service Discovery in Microservices.

Service discovery in microservices refers to the process by which services find and communicate with each other in a distributed architecture. In a microservices environment, services are often dynamically created, scaled, or removed, making it essential for them to locate one another without hardcoding their locations.

There are two main types of service discovery:

  1. Client-Side Discovery: The client is responsible for determining the location of the service it wants to call. It queries a service registry to get the list of available service instances and then chooses one to communicate with.

  2. Server-Side Discovery: The client sends a request to a router or load balancer, which then queries the service registry and forwards the request to an available service instance. The client does not need to know about the service instances' locations.

What is API Gateway in the context of Microservices?

An API Gateway acts as a single entry point for clients to access various microservices. Its importance includes:

  • Routing Requests: Directs client requests to appropriate microservices.
  • Load Balancing: Distributes incoming traffic to ensure optimal resource utilization.
  • Security: Centralizes authentication and authorization, enhancing security.
  • Rate Limiting: Protects backend services from being overwhelmed by requests.
  • Response Aggregation: Combines responses from multiple services into a single response to reduce client-side complexity.

How does Microservices architecture contribute to DevOps practices?

Microservices promote continuous delivery and deployment as each service can be developed, tested, and deployed independently. This aligns with the principles of DevOps, encouraging collaboration and automation.

What is the purpose of a Container in Microservices?

Containers provide a lightweight and consistent environment for running microservices. They encapsulate the application, its dependencies, and runtime, ensuring consistency across different environments.

What is the use of Docker?

Docker offers a container environment which can be used to host any application. This software application and the dependencies that support it which are tightly-packaged together.

Why are Container used in Microservices?

Containers are easiest and effective method to manage the microservice based application. It also helps you to develop and deploy individually. Docker also allows you to encapsulate your microservice in a container image along with its dependencies. Microservice can use these elements without additional efforts.

Explain Circuit Breaker pattern in Microservices.

The Circuit Breaker pattern is a design pattern used to detect and prevent failures in microservices by temporarily stopping requests to a failing service and redirecting those requests to a fallback mechanism.

How can you ensure data consistency in a Microservices architecture?

Ensuring data consistency in a microservices architecture can be challenging. One approach is to use the Saga pattern, where a sequence of local transactions is coordinated to achieve global consistency.

How independent micro-services communicate with each other?

It depends upon your project needs. However, in most cases, developers use HTTP/REST with JSON or Binary protocol. However, they can use any communication protocol.

Can you describe a situation where you successfully implemented a microservices architecture?

In a previous project, I led the migration of a monolithic e-commerce platform to a microservices architecture. We broke down functionalities into independent services such as user management, order processing, and inventory. We used Docker for containerization and Kubernetes for orchestration. By implementing an API Gateway and centralized logging, we improved performance and reduced deployment times from weeks to days. The result was enhanced scalability, allowing us to handle peak traffic during sales events without downtime.

What is the difference between microservices and serverless architecture?

A microservices architecture involves developing an application as a collection of small, autonomous services, each running in its own process and communicating over network calls.

In serverless architecture, developers write functions that a platform runs only when needed, without managing the underlying infrastructure. Serverless architecture is an event-driven execution model and is ideal for simple or single-purpose functions.

Continue Reading →

What is Microservice ?

Microservices are an architectural style that involves breaking down a large application into a collection of loosely coupled services that communicate over well-defined APIs. Each microservice is designed to perform a specific business function and can be developed, deployed, and scaled independently.

Here are some key characteristics and principles of microservices:

  1. Loose Coupling: Services are loosely coupled, meaning changes to one service don't require changes to others.
  2. Independent Deployment: Each microservice can be deployed independently, allowing for faster release cycles and reduced risk.
  3. Resilience: Failure in one microservice should not bring down the entire application. Services are expected to be resilient and handle failures gracefully.
  4. Scalability: Services can be scaled independently based on demand, optimizing resource usage.
  5. Technology Diversity: Each microservice can be implemented using different technologies, frameworks, and programming languages, as long as they communicate through standardized interfaces (typically APIs).
  6. Organizational Alignment: Microservices often align with DevOps principles, allowing development teams to take end-to-end ownership of services they develop and operate.
  7. Domain-Driven Design: Microservices are often organized around business capabilities or domains, which can improve development agility and maintainability.
  8. Data Management: Microservices may have their own databases, and data consistency between services is typically maintained through asynchronous communication and eventual consistency.
  9. Containerization: Microservices are often deployed in containers (e.g., Docker containers) to ensure consistency across different environments and simplify deployment.

What is API Gateway in Microservice?

In a microservices architecture, an API Gateway is a crucial component that acts as a single entry point for clients to interact with various microservices. It provides several important functions to facilitate communication between clients and the microservices behind it:

  1. Routing and Aggregation: The API Gateway routes incoming client requests to the appropriate microservices based on the request path, HTTP method, or other criteria. It can also aggregate multiple requests into a single one to reduce chattiness between clients and services.
  2. Protocol Translation: It can translate between different protocols (e.g., REST, WebSocket) used by clients and the internal protocols used by microservices.
  3. Request and Response Transformation: The API Gateway can modify requests and responses to adapt them to different schemas or versions, ensuring compatibility between clients and services.
  4. Authentication and Authorization: It handles authentication and authorization for incoming requests, ensuring that only authorized clients can access certain microservices or endpoints.
  5. Load Balancing: It can distribute incoming requests across multiple instances of a microservice to ensure optimal performance and scalability.
  6. Rate Limiting and Throttling: The API Gateway can enforce rate limits and throttling to protect microservices from being overwhelmed by too many requests.
  7. Logging and Monitoring: It can log requests and responses for auditing purposes and provide monitoring and analytics capabilities to track usage patterns and performance metrics.

Microservices Architecture Components

  1. API Gateway: A single entry point that handles incoming requests and forwards them to the appropriate microservices. It also handles common tasks like authentication, logging, and routing.

  2. Service Discovery: A mechanism for microservices to discover each other and communicate. It keeps track of service instances and their locations dynamically, especially important in large-scale systems.

  3. Load Balancer: Distributes incoming traffic to various instances of a microservice to ensure efficient use of resources and high availability.

  4. Database Per Service: Each microservice often has its own database to ensure independence and flexibility in choosing the right database technology for each service.

  5. Message Broker: For communication between services, message brokers such as RabbitMQ, Kafka, or NATS may be used to provide asynchronous communication and event-driven architecture.

  6. Logging and Monitoring: Tools for centralized logging (e.g., ELK Stack) and monitoring (e.g., Prometheus, Grafana) help ensure visibility and observability of all services in production.

How Microservices Communicate

  1. Synchronous Communication:

    • REST APIs: Services communicate with each other via HTTP using REST APIs. JSON is typically used as the data format.
    • gRPC: A high-performance, open-source RPC framework that allows services to communicate over HTTP/2, offering better performance and support for different languages.
  2. Asynchronous Communication:

    • Message Queues: Services communicate via message brokers like RabbitMQ, Kafka, or ActiveMQ. This approach decouples services and helps improve resilience.
    • Event-driven architecture: Microservices can emit events when a significant action happens (e.g., an order is placed), and other services react to those events asynchronously.

Tools and Technologies for Microservices

  1. Service Discovery:

    • Consul
    • Eureka
    • Kubernetes (with its built-in service discovery)
  2. API Gateway:

    • Kong
    • NGINX
    • Zuul (by Netflix)
  3. Message Brokers:

    • Apache Kafka
    • RabbitMQ
    • NATS
  4. Containerization:

    • Docker (for packaging microservices)
    • Kubernetes (for orchestration)
  5. Monitoring and Logging:

    • Prometheus, Grafana (for monitoring)
    • ELK Stack (Elasticsearch, Logstash, Kibana for logging)
  6. CI/CD:

    • Jenkins, GitLab CI, CircleCI
  7. Databases: Microservices may use various types of databases, including:

    • SQL databases (PostgreSQL, MySQL)
    • NoSQL databases (MongoDB, Cassandra)
    • Key-Value stores (Redis, DynamoDB)

By encapsulating these functionalities, the API Gateway simplifies the client-side experience and offloads common cross-cutting concerns from individual microservices. It promotes scalability, security, and flexibility in managing the interactions between clients and the microservices architecture.

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives