.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   静以修身俭以养德  阅读(1254)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2021-09-25 wangeditor遮挡其他控件
2010-09-25 数据绑定控件的ItemDataBound事件与System.Data.Common.DbDataRecord

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示