. NET MVC, Webapi,webform integration Steeltoe+springcloud implementation call the Service Center service summary

Source: Internet
Author: User

. NET integrated steeltoe for micro-service client registration and discovery requires the use of AUTOFAC dependency injection method, and mvc,webapi,webform three kinds of project types need to rely on the extension of the library are different, after two weeks of stepping pits, now do a superficial summary of it!

The following is a reference to the official Steeltoe documentation:

Package
App Type Description
Console/asp.net 4.x Steeltoe.Discovery.EurekaBase Base functionality. No Dependency Injection.
ASP. NET Core Steeltoe.Discovery.ClientCore Includes base. Adds ASP. NET Core Dependency Injection.
ASP. 4.x with AUTOFAC Steeltoe.Discovery.ClientAutofac Includes base. Adds AUTOFAC Dependency Injection.

Package
App Type Description
Console/asp.net 4.x Pivotal.Discovery.EurekaBase Base functionality. No Dependency Injection.
ASP. NET Core Pivotal.Discovery.ClientCore Includes base. Adds ASP. NET Core Dependency Injection.
ASP. 4.x with AUTOFAC Pivotal.Discovery.ClientAutofac Includes base. Adds AUTOFAC Dependency Injection.

After two weeks of their own attempts, based on the framework4.5.2+ Mvc,webapi,webform and other projects are basically using AUTOFAC way to service registration and invocation method of reference, so the need to introduce the expansion of the base is basically AUTOFAC end, Like the STEELTOE.DISCOVERY.CLIENTAUTOFAC and PIVOTAL.DISCOVERY.CLIENTAUTOFAC above.

Another class library We need to use includes:

Steeltoe.Common.Autofac

This class library contains methods for service discovery and invocation.

The

Three types of project directory structure is different, MVC and WEBAPI are Apicontroller interfaces, you can build the controller integration interface, and then directly with the AUTOFAC dependency injection method for the implementation of the micro-service invocation, the code can refer to the following:

public class Valuescontroller:apicontroller {private readonly discoveryhttpclienthandler _handler; Public Valuescontroller (idiscoveryclient client, iloggerfactory logfactory)//This is injection-dependent {_handler        = new Discoveryhttpclienthandler (client); }//Get api/values public async task<string> Get () {var client = new HTTPCL                       Ient (_handler, false); return await client.        Getstringasync ("Http://java-server/hi?name=demo"); }//Get API/VALUES/5 public string get (int id) {string re = id.                       ToString;                  return re;        }//Post api/values public void post ([frombody]string value) {}//PUT API/VALUES/5 public void Put (int id, [frombody]string value] {}//DELETE api/values/5 public void D elete (int id) {}}

  

So how does WebForm invoke the MicroServices method? This requires us to write a service class, implement a custom interface in the class, and invoke the method call to Steeltoe with dependency injection, and then rely on the page to inject its own class. Reference code:

Custom Service Interface class IFetchService.cs:

Public interface Ifetchservice    {        task<string> randomfortuneasync ();    }

Customize the service class and complete the dependency injection and implementation of the Steeltoe interface method FetchService.cs:

public class Fetchservice:ifetchservice    {        discoveryhttpclienthandler _handler;        Private Const string Random_fortune_url = "Http://java-service/hi?name=tian";        Private ilogger<fetchservice> _logger;        Public Fetchservice (idiscoveryclient client, iloggerfactory logfactory = null)        {            _handler = new Discoveryhttpclienthandler (client);            _logger = Logfactory?. Createlogger<fetchservise> ();        }        Public async task<string> Randomfortuneasync ()        {            _logger?. Loginformation ("Randomfortuneasync");            var client = Getclient ();            return await client. Getstringasync (Random_fortune_url);        }        Private HttpClient getclient ()        {            var client = new HttpClient (_handler, false);            return client;        }    }

Next, the most important step, the configuration of dependency injection in the program global file Global.asax, the AUTOFAC extension libraries referenced here are also different:

MVC directly references AUTOFAC can

WEBAPI is referring to Autofac.webapi2.

WebForm is referring to Autofac.web.

Here the main write down the WebForm configuration code:

 public class Global:System.Web.HttpApplication, icontainerprovideraccessor {//Hold provider for application container static I        Containerprovider _containerprovider;        will be used by ' AUTOFAC httpmodules ' to parse and inject the instance properties of the dependency.        Public Icontainerprovider Containerprovider {get {return _containerprovider;} } protected void Application_Start (object sender, EventArgs e) {Applicationconfig.registerconfig            ("development");            var config = globalconfiguration.configuration;            var builder = new Containerbuilder (); ADD Microsoft Options to Container builder.            Registeroptions (); ADD Microsoft Logging to Container builder.            Registerlogging (applicationconfig.configuration); ADD Console logger to container builder.            Registerconsolelogging (); Register all the controllers with Autofac Builder. Registerassemblymodules (assembly.getexecutingassembly ());            Register idiscoveryclient, etc. Builder.            Registerdiscoveryclient (applicationconfig.configuration); Register Fortuneservice Builder. Registertype<fetchservise> ().                      As<ifetchservise> (); Builder.            Registerwebapimodelbinderprovider (); Create the AUTOFAC container var container = Builder.            Build ();            _containerprovider = new Containerprovider (container); Config.                        Dependencyresolver = new Autofacwebapidependencyresolver (container); Get a logger from container//var logger = container.            Resolve<ilogger<webapiapplication>> (); Logger.            Loginformation ("Finished container build, starting background services"); Start the Discovery client background thread container.            Startdiscoveryclient (); Logger.       Loginformation ("Finished starting background services"); } protected void Session_Start (object sender, EventArgs e) {} protected void Application_beg Inrequest (object sender, EventArgs e) {} protected void Application_AuthenticateRequest (object Sende        R, EventArgs e) {} protected void Application_Error (object sender, EventArgs e) {}  protected void Session_End (object sender, EventArgs e) {} protected void Application_End (object sender, EventArgs e) {}}

  

Then the dependency injection in the page code page implements our custom interface method:

public partial class WebForm2:System.Web.UI.Page    {public        ifetchservise fetch {get; set;}        protected void Page_Load (object sender, EventArgs e)        {this            . Page.registerasynctask (New PageAsyncTask (GetName));        }        Private async Task GetName ()        {            Label1.Text = await fetch. Randomfortuneasync ();        }    }

  

 

. NET MVC, Webapi,webform integration Steeltoe+springcloud implementation call the Service Center service summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.