Creating Services With Azure Service Fabric

Introduction

 
In this article, we are going to create microservices using Azure Service Fabric SDK. First, you'll learn how to set up the environment. Next, you'll be introduced to the Service Fabric reliable services. We will actually build two microservices, one stateless and one state-full. We will also go through options of how you are supposed to implement communication in distributed microservice scenarios, and we'll connect our microservices together.
 

Roadmap

  1. Building the environment

    1. Getting Visual Studio Ready
    2. Installing Azure Service Fabric SDK

  2. Introduction to Reliable Service
  3. Creating a Product Catalog
  4. Building Product Catalog Service
  5. Creating a Web API
  6. Connecting Two Services Together
  7. Test Using Postman
  8. Use Cases

Building the environment to use Azure Service Fabric

 
I’ll suggest you use Visual Studio 2019 where it works seamlessly.
  • First of all, open the Visual Studio Installer, find your installed VS version, and click "Modify".

    Creating Services With Azure Service Fabric

  • Then, click on "Individual Components" tab.

    Creating Services With Azure Service Fabric

  • Scroll down and make sure the "Service Fabric Tools" option is checked. If not, check it and then let the Visual Studio Installer install it.

    Creating Services With Azure Service Fabric

  • Now, install AzureService Fabric SDK. The easiest way is through the Microsoft Web Platform Installer. If you don’t have Web Platform installer, navigate here and click “Install this extension”.

    Creating Services With Azure Service Fabric

  • Open the Web Platform installer and in the search bar, enter “Service Fabric SDK” and install the highlighted version. Don’t install SDK and Tools because these are for previous Visual Studio versions.

    Creating Services With Azure Service Fabric
Now, our environment is ready and we can start playing with Service Fabric.
 

Introduction to Reliable Service

 
In the Azure Service Fabric world, any process which runs in the background is called a reliable service. Therefore, these two services that we are going to build are reliable services. With reliable services, you get a simple programming model, access to Azure Service Fabric API, access to Reliable storage and a Pluggable communication model.
 

Creating a Product Catalog (stateful service)

  • Open Visual Studio, click on "Create a new project", and select project type as “cloud” to filter results. Now, select "Azure Service Fabric Application" and click "Next".

    Creating Services With Azure Service Fabric

  • Configure your project.
    • Project name: Any meaningful name; I’m using Ecommerce
    • Location: Provide a path for the project
    • Solution name: same as the project name

      Creating Services With Azure Service Fabric

  • Choose Stateful Service for our product catalog service and name it as Ecommerce.ProductCatalog.

    Creating Services With Azure Service Fabric
After the solution is generated by Visual Studio, you can see two projects in here. The first project, Ecommerce is a Service Fabric project. Basically, it contains a description of how to deploy the application, what are the application parameters, and which services it consists of. The other project, ECommerce.ProductCatalog, is an implementation of the service. Visual Studio project generator creates one so we can get a complete, compilable, deployable, and working application. Otherwise, there will be no point, right?
 
Creating Services With Azure Service Fabric 
 
Let’s explore the Program.cs file in Ecommerce.ProductCatalog service project. Simply, it does three things.
  1. It registers the Reliable Service,
  2. Log Reliable Service has started,
  3. Sleep forever.
Simple enough, right?
 
Creating Services With Azure Service Fabric 
 
Building Product Catalog ServiceNow let's have a look what's inside that service class that we just registered. ProductCatalog class is the entry point to our service. Azure Service Fabric creates an instance of this service when it's deployed and passes a service context. The context can be used to access various information about the service environment. CreateServiceReplicaListeners is called by Azure Service Fabric to create communication and points for your service.
 
Creating Services With Azure Service Fabric 
 
And RunAsync is called when your service is started. This is where you can run code which executes in the background or perform some heavy initialization logic.
 
Creating Services With Azure Service Fabric
 

Building Product Catalog Service 

 
Back to our solution in Visual Studio, and the first thing I'm going to do is create another project of class library type. I'll call it ECommerce.ProductCatalog.Model, and the purpose of it will be store classes shared between microservices.
  • Add a Class Library Type project and name it as ProductCatalog.Model

    Creating Services With Azure Service Fabric

    Creating Services With Azure Service Fabric

    As the name implies, the product catalog is a service that will be responsible for storing information about products our imaginary shop is selling. To keep the thing simple, we will declare the Product entity as a class, which contains only a few fields. It will have a unique ID of type GUID, a name of a string type, a short description, the price, and availability showing you how many products are in stock at the moment.

  • Create a class Product in the ProductCatalog.Model project with these members.

    Creating Services With Azure Service Fabric

  • Add a reference of the Model project to our Product Catalog project.

    Creating Services With Azure Service Fabric

    Creating Services With Azure Service Fabric

    Now, let's build an interface which contains methods for saving and retrieving the products. The first method I defined simply returns the list of all products, and the second one adds a new product of the database. Note that all the methods are asynchronous. They return a task, and the reason for that is that most of the Service Fabric APIs are asynchronous to achieve the best performance possible.

  • Create a public Interface with the following methods to implement,

    Creating Services With Azure Service Fabric

    Okay, now let's implement our interface. I'll create a new class called ServiceFabricProductRepository, and implement the interface methods.

  • Create class ServiceFabricProductRepository to implement that interface,

    Creating Services With Azure Service Fabric

    And before we proceed, In order to talk to the reliable storage, we'll need to have a reference to IReliableStateManager. This is a built-in Service Fabric interface to work with storage, so I'll add a constructor which requires it. The simplest way to store the products is to use something called a reliable dictionary. It's almost identical to a normal C# dictionary collection, but it's reliable. The dictionary maps directly on Service Fabric storage. In order to get a reference to this dictionary, I'll use GetOrAddAsync method, which means I'd like to get a reference to a dictionary called Products, or if it doesn't exist, just create it and return me an empty reference, has the name get or add. Now all the operations in Service Fabric require a transaction, just like working with a database transaction. This is a good thing because Service Fabric commits changes on disk only after a transaction is committed, and if an error occurs, the whole thing gets reverted. I'll request the transaction object from the state manager and make a call to add the product, or update it if it already exists, and commit the transaction. That's it for adding the product.

  • Implement first method AddProduct(Product product)

    Creating Services With Azure Service Fabric

    Moving on to the next method. Same as before. First of all, I'll request an enumerator object from Service Fabric, and then asynchronously enumerate all the elements inside it. This code looks long and weird and getting each element incurs a call to Service Fabric because it doesn't just return only elements. The reason for that is that you might have millions of objects in your collection and Service Fabric will store and retrieve them effectively. And to protect your code from locking up, the API is asynchronous, meaning that other tasks can still run effectively while the code is enumerated in that huge collection. In reality, you shouldn't store that many objects in one collection, but this is just a demo exercise.

  • Implement second method GetAllProducts()

    Creating Services With Azure Service Fabric

    Time to use our storage repository, so let's head back to our ProductCatalog service class and invoke it. Navigate to the RunAsync method and delete all the default generated code. We don't need it in here. I will declare a variable of type IProductRepository as a class member so we can use it later.

  • Declare a variable type IProductRepository in Productcatalog.cs

    Creating Services With Azure Service Fabric

  • Head back to RunAsync and create an instance of it we've just implemented.

    Creating Services With Azure Service Fabric

    As you can see, I'm passing the state manager here because every stateful service has a StateManager property defined on its base class, so we can use it.

  • Create a few fake products when the service starts and add them to the database one by one.

    Creating Services With Azure Service Fabric

    Creating Services With Azure Service Fabric
That's how simple it is to store the data in Azure Service Fabric. Now that we've created product catalog stateful service, let's get to building the front-end service, which allows external users to use our system.