.Net Core 静态类获取注入服务

由于静态类中无法使用有参构造函数,从而不能使用常规的方式(构造函数获取) 获取服务,我们可以采取通过IApplicationBuilder 获取

1.首先创建一个静态类

 1 using Microsoft.AspNetCore.Builder;
 2 using Microsoft.AspNetCore.Http;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace OnlineTest.Tools
10 {
11     public static class ServiceLocator
12     {
13         public static IServiceProvider Instance { get; set; }
14 
15         public static IApplicationBuilder ApplicationBuilder { get; set; }
16 
17         
18     }
19 }

2.再去setup中的Configure 方法中获取 IApplicationBuilder  对象

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        //此方法由运行时调用。使用此方法配置HTTP请求管道
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ServiceLocator.Instance = app.ApplicationServices;
            ServiceLocator.ApplicationBuilder = app;

            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "知行.Api v1"));
            if (env.IsDevelopment())
            {

            }
     }

3.在需要使用的地方直接拿就ok了

  var serviceScope= ServiceLocator.ApplicationBuilder.ApplicationServices.CreateScope();
  var _dictionaryEntityBL = serviceScope.ServiceProvider.GetService(typeof(IDictionaryEntityBL)) as IDictionaryEntityBL;

  

posted @ 2022-06-28 10:32  echo_sw  阅读(2667)  评论(0编辑  收藏  举报