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

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

1.首先创建一个静态类

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OnlineTest.Tools
{
    public static class ServiceLocator
    {
        public static IServiceProvider Instance { get; set; }

        public static IApplicationBuilder ApplicationBuilder { get; set; }


    }
}

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 on 2022-09-25 16:04  静以修身俭以养德  阅读(1226)  评论(0编辑  收藏  举报

导航