Implement Microservices with Ocelot API-Gateway in .NET

By:   |   Updated: 2024-10-08   |   Comments   |   Related: > Application Development


Problem

Monolithic architecture no longer seems to be in vogue, one of the reasons being that digital software is becoming more complex and complicated. Microservices architecture is gaining popularity slowly and steadily. No wonder every app development project worldwide favors the concept. The task at hand is to implement a Microservice with Ocelot API gateway in .NET. Read away to know more.

Solution

The web development realm keeps evolving. What looked modern and was the talk of the town yesterday can vanish overnight, and who knows, certain trends that were once dismissed as irrevocably passé can unexpectedly gain the top spot all over again.

In the following tip, we will cover one such trend that doesn't have any propensity to change overnight anytime soon. Yes, I am talking about none other than the microservices architecture. We have witnessed numerous architectural patterns and best practices for so many years. Among these unforgettable names that instantly come to mind is microservice architecture when looking for the following qualities:

  • Rich concerning scalability
  • Flexibility
  • Domain-driven design
  • Robustness
  • Continuous delivery
  • Infrastructure automation
  • Uniqueness
  • Polyglot programming and persistence
  • Ease of maintenance

We will discuss what microservices architecture is, why more and more organizations are trending towards the concept, and an easy step-by-step guide to implement microservices using the Ocelot API gateway in. NET. So, let's get started!

About Microservice Architecture

The term was coined by Robert C. Martin. At that point in time, the concept was pretty simple, mainly focusing on combining those things that usually change for the same reason and separating those that change for unusual or different reasons.

In simple words, microservices architecture is a sure-shot approach to systematically breaking down a software system into small, independent services. No wonder more than 80% of companies, including small, medium, and large enterprises across the globe, are focusing on this technology.

Speaking further about the microservice architecture, it even works wonders for loosely coupled services, especially the ones that need to be developed, deployed, and maintained successfully. When the system is broken down, the overall development speed increases, meaning a quick time to market is possible. Apart from this, in case a small failure occurs, the entire system no longer needs to be redeveloped. Of course, this surely results in increased overall productivity and efficiency of the team.

Interestingly, microservices were once mainly considered for backend solution development project assistance. This no longer seems to be the case. Every service incorporated here is highly responsible for conducting discrete tasks, and not just that. Here, seamless communication can be established, all thanks to APIs. So, if you face any complicated business problem, you no longer have to worry.

Now, let us delve more into where it all started.

Have you ever come across monolithic applications? Well, the term was specially coined for those applications featuring a single server and three layers: presentation, application/business logic, and database. Each was developed in a single stack and intertwined in the data center.

Users were supposed to successfully interact with the presentation layer, which communicated with the business logic and database layers, and then the information returned to the end user. No matter how efficient this approach seemed, it consisted of several loopholes and aspects that led to multiple failures. And to be precise, the concept of self-healing didn't exist back then, so human intervention was needed.

Cut to the mid-2000s when the architecture began to change, and various layers were incorporated outside the single server and independent service silos. Now, admin experts must aggregate servers and seamlessly scale services. This approach simply led to shorter development cycles, decoupling services, and better high-availability solutions. Overall, this approach was far better than monolithic applications on bare-metal servers.

Microservices seem to have collaborated successfully with .Net, Docker containers, and cloud-native architectures, which means it is compatible with different operating systems. And since these are loosely coupled, keeping the app functionality intact is possible. Data transfer is seamlessly done through the HTTP/HTTPs connection. Every service features precise processing power and network resources. Even if there is a major failure, nothing happens to the overall app functionality. Now, it's time to focus on the pure benefits or advantages offered by the microservices architecture.

Benefits of Microservices

High Scalability

The first and foremost benefit to take into account is high-end scalability. When working on microservices architecture, teams can now easily introduce new components with no or minimal glitches or downtime. Since every service within the architecture is independent, one no longer needs to worry about compatibility concerns.

Now, I have come across several developers who tend to deploy services across multiple servers. This usually mitigates performance, especially due to all the individual components, and there is no scope for companies to vendor lock.

Continuous and Quick Deployment

When we used monolithic architecture, one change led to redeployment of the entire application. Fortunately, with the inception of microservices architecture, quick and constant deployment or releases are possible because each service evolves or changes are made on an individual basis. Decoupling services surely enhances agility, and updates can be rolled out in a swift manner. Above all, minimal fixes don't interrupt the entire system.

Great Flexibility

The next benefit to take into consideration is greater flexibility. Different teams are roped in to deploy different services simultaneously, resulting in a quick deployment procedure, and one can add or remove features and functionalities at any point.

In addition, you see there are times when businesses, especially during their expansion phase, must outsource certain functionalities to reputable and reliable third-party partners. While doing so, they are concerned about protecting intellectual property. This was not possible with the conventional monolithic format. With a microservices architecture, it is possible to specifically choose tech partners who won't disclose core services.

Resilience

Another core advantage of considering microservices architecture is absolute resilience. As long as the system is broken down and services are tweaked on an individual basis, one failure cannot hinder the overall performance of the application.

In addition to resilience, these microservice architectures are quite cost-effective. Since all the services can be created and maintained independently, it is possible for quick development and deployment, resulting in a lower price.

Enhanced Support and Maintenance

The next interesting advantage offered by microservice architecture is it ensures full-fledged support and maintenance. Small chunks are usually easy to maintain. Whether it's about deploying specific changes, testing its overall functionality, or optimizing the performance to a certain level, there is no scope for an issue at all.

Apart from seamless support and maintenance, another factor worth acknowledging here is that experimenting or coming up with different innovative ideas becomes quite normal with microservices architecture. This means that the newest features can be rapidly rolled out, and if customers do not like it, rolling them back isn't an issue.

Full-fledged Secured

In a world full of uncertainties and security threats, considering technology that offers full-fledged security is a must. When a large system or solution is successfully broken into smaller pieces, the scope for unnecessary intrusion or problems gradually decreases. This doesn't mean there is no connection between the smaller chunks.

Moreover, microservices ensure businesses come up with more granular approaches, especially regarding data security. In addition to security, having enough compliance is very important because GDPR and HIPAA must be adhered to, especially in how businesses take care of vital information and data. More often than not, secure APIs are considered favorable for connecting microservices. And why not, since doing so ensures safe authorization for the end users?

Technological Diversity

Here, all services are pretty independent; developers can easily choose from their arsenal of tools and technologies to streamline the entire development procedure. There is a huge scope for innovation, experimentation, and reduction in technological dependencies, especially between modules.

Disadvantages of Microservices

Increased Development Procedure

One of the major disadvantages of considering microservices architecture is that dividing the app into smaller chunks can result in more time and effort consumed.

Managing Data Can Be Tricky

Another disadvantage to take into account is that managing tons of data can be tricky, tiresome, and daunting. This is especially the case when each service is comprised of an independent database; data consistency and integrity become quite a concern.

Highly Complicated

Lastly, the level of complexity turns out to be pretty high. Wondering why? Well, microservices architecture mainly comprises technology of a greater variety. And, its distributed nature is way more complex and complicated due to consistency, synchronous communication, and network latency.

Step-by-Step Tutorial

Step 1

Download the latest version of the .Net framework (.Net 8.0 at the time of writing).

Download .NET 8.0

Step 2

Install the .NET software.

Modify Setup

Step 3

Click Visual Studio IDE and begin a new project.

Open the Visual Studio IDE and create a new project

Step 4

Now, have you come across the term blank solution? Well, it is said that when the new project requires it to be empty or there are no pre-saved projects available.

Create a blank solution

Step 5

Provide a suitable name for the new project. Click Create.

Name to your new project

Step 6

Right-click within the Options menu, choose Add, then click Create. The next thing you need to do is click on the New Project.

Add New Project

Step 7

A wide range of options will appear. It is strongly recommended that you type "Webapi" in the search bar. Choose ASP.NET Core Web API and click Next.

ASP.NET Core Web API

Step 8

Save the location precisely and click Next.

Click Next

Step 9

Configure the project with the remaining additional information needed, and click Create.

configuring some additional information

Step 10

As mentioned earlier, microservices architecture comprises a wide range of services. Let's add new services beginning with ShoeService. Click Next.

Add New Serivce

Step 11

After that, choose another service, such as ClothesService. Click Next. Continue adding services for your project.

Add another service

Step 12

Once you are finished adding services, create a GET method for each service.

Create a GET Method

Step 13

Doing so returns the shoe list with the route GetShoes and, similarly, the clothes list with the route Getclothes.

Create a GET Method

Step 14

Next, right-click on ApiGateWay. Go to Options and choose Manage NuGet Packages to add Ocelot.

Manage NuGet Packages

Step 15

Usually, Ocelot is found in the NuGet package, so choose it and add it to your project.

Find Ocelot in NuGet

Step 16

Next, we need to add middleware and services of the tech. Make sure it is done within the program.cs file.

Services of Ocelot

Step 17

Now, add services with the JSON file. Right-click on the APIGateWay project, choose Add, and click on New Item.

Add new Item

Step 18

Do not forget to add the shoe service in the JSON file. You can take a look at the image for reference purposes. Click Add.

Add Service

Step 19

Once you are done with that, you will be successfully directed to the solution explorer. Again, you have to follow the same procedure which is right click, go to "Add" and click "New Item".

Add New Item

Step 20

Much like the shoe service, add the clothes service with the JSON file.

Add Service

Step 21

Repeat the procedure by right-clicking on the ApiGateWay project and choosing the new item.

API Gateway

Step 22

Now, add Ocelot to the existing JSON file.

Add Ocelot

Step 23

Have you figured out the actual route for the shoe service, if not then you must and send a request to the ShoesController from APIGateway.

Determine Route

Step 24

Much like the above step, it's time to focus on the route for the clothes service to send a request to the ClothesController from APIGateway.

Determine Route

Step 25

And we are almost done here. Let's successfully configure the GET URL.

Configure GET URL for Shoe Service

Step 26

Lastly, a similar step for the clothes services as well.

Configure GET URL for Clothes service

Conclusion

Every technology has its fair share of advantages and disadvantages. The key is to weigh them precisely and make the choice. For example, if you want to simply develop, deploy, scale, and manage the services of an app as a single unit, then choose a monolithic approach. If you are willing to manage the services independently, look no further than microservices architecture.

In a nutshell, you must know that both .Net technology and microservices architecture work wonders like peanut butter and chocolate; one can never go wrong with such a combination. However, the most preferred way to implement microservices using the .Net technology is by considering the Docker images.

I hope this tip was insightful. In case you still have any doubts or queries, feel free to reach out in the comment section below.

Next Steps

Check out these other Microservices articles:



sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Albert McQuiston Albert McQuiston is a software developer with more than 10 years of experience. He has worked with many companies and holds a bachelor's degree in Computer Science.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2024-10-08

Comments For This Article

















get free sql tips
agree to terms