首先什么是微服务:微服务个人理解就类似于后台的接口。将业务/功能封装成一个个的微服务,拆分开来让。(可以理解为封装的静态类。但是比静态类更灵活。可以多态。如果注册的微服务是单例就和静态类一样)。增强了代码的高内聚,低耦合。

 创建自己的微服务

         1.创建微服务的基类接口。

         

        2.创立一个类继承这个接口。实现方法  (这里只是示范。建议创建泛型类。提高灵活性)

        

        3.在管道的前端注册微服务 (微服务只需要在管道前端注入,不需要再后面后端使用。)

 public void ConfigureServices(IServiceCollection services)
 {
      services.AddMvc();

      //写法1
      services.AddScoped(typeof(ServerInterface), typeof(ServerTest1));     //每次请求,都获取一个新的实例,同一个请求获取多次会得到相同的实例。
      services.AddTransient(typeof(ServerInterface), typeof(ServerTest1));  //每次请求,都获取一个新的实例,即使同一个请求获取多次也会是不同的实例
      services.AddSingleton(typeof(ServerInterface), typeof(ServerTest1));  //单例模式,每次都获取同一个实例

      //写法2
      services.AddScoped<ServerInterface, ServerTest1>();       //每次请求,都获取一个新的实例,同一个请求获取多次会得到相同的实例。
      services.AddTransient<ServerInterface, ServerTest1>();    //每次请求,都获取一个新的实例,即使同一个请求获取多次也会是不同的实例
      services.AddSingleton<ServerInterface, ServerTest1>();    //单例模式,每次都获取同一个实例(和静态类几乎一样)

}

 

     4.代码中的应用

   // 1.构造函数的引用 (适用于全局使用)
   public class NewCompanyDetailInfoController : Controller
   {
        //全局的efserver
        private IEFSever efserver;
        public NewCompanyDetailInfoController(IEFSever eFSever) => efserver = eFSever;

        //2. 方法的引用。 (仅有某个方法可以使用服务)
        public async virtual Task<object> GetCompanyDeatilHeadInfo(User user,[FromServices] ITimeHandleServer timeHandleServer)
        {
            return "";
        }

   }

 


  微服务的单例模式其实和静态类相似。但是比静态类支持更多种的实例化方法。

还分享一个注入的小方法。


首先我们要了解程序的运行机制。

程序的入口都是从Main方法入口的

    public class Program
    public static void Main(string[] args)
    {

            IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", false, true).Build();
            CreateWebHostBuilder(args, configuration).Build().Run(); 
    }

      public static IWebHostBuilder CreateWebHostBuilder(string[] args, IConfiguration configuration) =>
            WebHost.CreateDefaultBuilder(args)
            .UseUrls(configuration["UseUrls"])
            //.UseUrls("http://*:8001")
            .UseStartup<Startup>();

然后。在Main 方法中再创建服务管道。默认读取默认的配置文件。可以进行自定义的配置文件的指定。(这里的startup其实就是默认的配置文件)

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();//添加本系统的内存机制 
            services.AddLogging();
            services =SeverRoot.AddSever(services); //微服务的注册
              
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
         
            //app.UseHttpsRedirection();
            app.UseCors("AllowAnyOrigin");
            app.UseMvc();
        }
    }

然后Main方法载入配置文件。读取管道的头部。在ConfigureServices中 注入管道中添加的香项目。 再在Configure中使用管道中注入的组件等。 其中之前 创建微服务 第3步 中的定义就是在ConfigureServices中的。比较特殊的是。微服务是微软优化后的组件。不需要在管道末端use使用。 

 而扩展就是。你可以在注入中。

自定义的将管道的对象进行操作。如果一个程序中微服务。都写在ConfigureServices中那么会很长一串再配置文件中。暴露了很多。且不美观。所以可以自定义一个类。进行注入在管道头部中进行注入。统一进行管理且简洁。  这种方法还可以应用到其他对象中。可以自定义的给管道中注入许多你需要的东西。

     AddScoped<>();       //在同一个Scope内只初始化一个实例 ,可以理解为( 每一个request级别只创建一个实例,同一个http request会在一个 scope内)
     AddTransient<>();    //每次请求,都获取一个新的实例
     AddSingleton<>();    //单例模式,每次都获取同一个实例(和静态类几乎一样)

    public static class SeverRoot
    {
        /// <summary>
        /// 微服务注册
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddSever(IServiceCollection services)
        {
      services.AddScoped<ServerInterface, ServerTest1>();       //每次请求,都获取一个新的实例,同一个请求获取多次会得到相同的实例。
      services.AddTransient<ServerInterface, ServerTest1>();    //每次请求,都获取一个新的实例,即使同一个请求获取多次也会是不同的实例
      services.AddSingleton<ServerInterface, ServerTest1>();    //单例模式,每次都获取同一个实例(和静态类几乎一样)


            return services;
        }
    }

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐