Click here to Skip to main content
15,891,316 members
Articles / Programming Languages / C#

Microservices in brief

Rate me:
Please Sign up or sign in to vote.
4.29/5 (4 votes)
25 Apr 2016CPOL4 min read 18.8K   14   4
This article is a brief and comprehensive take on the concept of implementing micro services.

Introduction

In the ocean of technologies, emerged a new one - Micro Services, attracting all geeks with everything that it offers. This article is a quick tour, showcasing its strength and an illustration of its implementation.

Background

Microservice: It is a term budding up with a great pace lately. Earlier, when I heard of it for the first time, I thought it to be a new breed of service. But as I dived into the topic, it emerged out to be an application development style using completely seggregated, mutually exclusive, small scoped services with decentralized control of data and languages.  This style of application development is mostly favourable for distributed application architecture.

Lets try and understand it with an example. Earlier monolithic application architecture had 3 tier:

1. Client

2. Service layer ( business layer, validation layer, CRUD operations on database), mostly implemented as a single service.

3. Database

 

But here in this new style of application development, our client and database tier remains the same, the main focus is on the second tier - the services. By the basic concept of microservices. this second layer is broken  into multiple single unit services performing a mutually exlcusive task.

 

Features:

1. Loosley coupled, more cohesive: Emphasis is on building components that is replaceable and upgradable without causing much fuss. Suppose, when all deployed under one common project. Then a minute change in one service results in redeployment of all services. However, with this approach, one can easly deploy that particular service without affecting the rest, 

 

2. Scalability Of Application Server: Our application server hosts all the services, for load balancing, multiple instances of application server can now be avoided, simply scale out the currently running microservice and when the job of respective service is over, scale in it, and scale out the service, next to deliver.

3. Resuability quotient is high: Since each microservice is a self sufficient component and can exist independently. This very feature makes it the service of time. Each service acts as the pluggable building block for re use at a later point of time with some other project. 

 

Note: With the introduction of micro services, industry has generated an all time dependency on the developers of microservice. The team developed a micro service is held as responsible for its maintainance through out.  "You build it, you run it." .

 

When to know, its time for a new microservice? 

Always ask below questions to yourself, and as an answer you would know if you need another microservice breakdown:

a. Did I create a deployment dependency?

b. Who owns it?

c. Does it fit the scalability/ availability criteria?

d. Does it has its own deplyment cycle?

c. Can a different team develop it.

 

Illustration of impelementing a microservice:

There are different ways to implement a microservice:

a. REST

b. RPC

c. SOAP

In my opinion best way is to go for a stateless service - Rest service.

Therefore, down here I am proceeding to implement a WCF- REST service.

 

1. Open a Visual Studio instance and select WCF service library project.

2. Name the solution as the specific task that service is going to provide. 

Using the code

3. Create the service interface with the contracts.

 

C++
namespace GetAllAlertsRestService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IGetAllAlertsService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, UriTemplate = "myxml")]
        GetAlertsResponse GetAllXMLDataAsString();

        [OperationContract]
        

        GetAlertsResponse GetAllJSONDataAsString();
        // TODO: Add your service operations here


        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/PostString",
         RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
        bool PostXMLData(string value);
    }

   
}

4. Implement the service contracts in your service class.

 

 

C#
namespace GetAllAlertsRestService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
    public class GetAllAlertsService : IGetAllAlertsService
    {  
        GetAlertsResponse IGetAllAlertsService.GetAllJSONDataAsString()
        {
            GetAlertsResponse responseObject = new GetAlertsResponse() { Response = "no data available." };
            return responseObject;
        }

        GetAlertsResponse IGetAllAlertsService.GetAllXMLDataAsString()
        {
            return new GetAlertsResponse() { Response = ResponseStorage.ResponseString };  
        }       
        
        private void GetUpdatedData()
        {
            
        }

        public bool PostXMLData(string value)
        {
            if (value != null)
            {
                ResponseStorage.ResponseString = value;
            }
            return true;
        }
    }
} 

 

5. Now open another visual studio instance and add a console application ( we are going to host the service in another console application).

 

6. Copy the below code in your app config.

C#
<!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->

<system.serviceModel>
    <bindings>
      <wsDualHttpBinding>
        <binding name="NewBinding0" openTimeout="00:05:00" sendTimeout="00:05:00" />
      </wsDualHttpBinding>
    </bindings>
    <services>
      <service name="GetAllAlertsRestService.GetAllAlertsService">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
          bindingConfiguration="" contract="GetAllAlertsRestService.IGetAllAlertsService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>  
          <!--<baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/GetAllAlertsRestService/GetAllAlertsService/" />
          </baseAddresses>-->
        </host>
      </service> 
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>

      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

The WCF Rest service is supposed to be of WebHttpBinding and behaviour configuration as webHttp.

 

6. In programs.cs file of the solution:

C#
namespace HostRestWCFService
{
    class Program 
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8733/Design_Time_Addresses/GetAllAlertsRestService/GetAllAlertsService/");

            ServiceHost hostService1 = new ServiceHost(typeof(GetAllAlertsService),baseAddress);
            hostService1.Open();
            Console.WriteLine("Service - GetAllAlertsRestService is hosted..."); 
            Console.WriteLine("Press enter to stop the services.");
            Console.ReadLine();
            hostService1.Close();        
        }
    }
    
}

 

7 Build both the solution, and start the service hosting solution:

Hit the url from browser as mentioned in the host application. 

I hit the url as : "http://localhost:8733/Design_Time_Addresses/GetAllAlertsRestService/GetAllAlertsService/"

Now append the url of above given service with what mentioned in your service contracts:

 

This is what I did:

"http://localhost:8733/Design_Time_Addresses/GetAllAlertsRestService/GetAllAlertsService/myxml".

and this is what I got:

 

 

With above illustration, I have tried to ensure, that GetAllAlertsService( Rest service) is self deplyable, self sufficient, and have a distinct functionalty to expose. This service can be deployed at any application server, and client from any machine can simply access it over the browser by using url ( having app server ip or domain name, instead of localhost).

 

History

1st Version - Creation of the Article. - 25th April, 2016

2nd version - Updated links for images. - - 25th April, 2016

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCan't get it to work Pin
Ed(Member 1767792)29-Nov-18 16:19
Ed(Member 1767792)29-Nov-18 16:19 
Cannot get this example to build without knowing what the 'GetAlertsResponse' type is defined as.
QuestionDive-into-Microservices-Architecture-Part-I Pin
Aydin Homay1-Nov-18 0:32
Aydin Homay1-Nov-18 0:32 
QuestionToo brief Pin
Duncan K G Campbell10-Mar-17 17:09
professionalDuncan K G Campbell10-Mar-17 17:09 
AnswerRe: Too brief Pin
Yashashwi Srivastava19-Mar-17 23:13
Yashashwi Srivastava19-Mar-17 23:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.