首页 > 其他分享 >net6 类中获取服务

net6 类中获取服务

时间:2024-04-16 12:13:23浏览次数:21  
标签:ServiceLocator 获取 GetService Instance static var net6 public 类中

第一种实现方式(不推荐)

var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
var _demoService = provider.GetService<IDemoService>();

var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
var _demoService = provider.GetService<IDemoService>();

 

第二种实现方式(推荐)

.net6实现方式

public static class ServiceLocator
{
public static IServiceProvider Instance { get; set; }
}

--program文件中
var app=buidler.Build();
ServiceLocator.Instance =app.Service();


--demo方法
public void DemoMethod()
{
var demoService = ServiceLocator.Instance.GetService<IDemoService>();
}


复制代码
public static class ServiceLocator
{
 public static IServiceProvider Instance { get; set; }
}

--program文件中
var app=buidler.Build();
ServiceLocator.Instance =app.Service();


--demo方法
public void DemoMethod()
{
 var demoService = ServiceLocator.Instance.GetService<IDemoService>();
}
复制代码

.net core 3.1实现方式

public void Configure(IApplicationBuilder app)
{
ServiceLocator.Instance = app.ApplicationServices;
}

public static class ServiceLocator
{
public static IServiceProvider Instance { get; set; }
}


public void DemoMethod()
{
var demoService = ServiceLocator.Instance.GetService<IDemoService>();
}


复制代码
public void Configure(IApplicationBuilder app)
{
 ServiceLocator.Instance = app.ApplicationServices;
}
 
public static class ServiceLocator
{
 public static IServiceProvider Instance { get; set; }
}
 
 
public void DemoMethod()
{
 var demoService = ServiceLocator.Instance.GetService<IDemoService>();
}
复制代码

 

注意:使用ServiceLocator.Instance.GetService()只能获取AddTransient和AddSingleton注入的对象,而不能获取AddScoped(请求生命周期内唯一)注入的对象,因为获取的对象和构造函数获取的不是同一个(即获取的对象没有共享),使用场景比如IUnitOfWork。
那怎么手动获取请求生命周期内的注入对象呢?方法如下:

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Domain
{
public class DemoService : IDemoService
{
private IUnitOfWork _unitOfWork;

public DemoService (IHttpContextAccessor httpContextAccessor)
{
_unitOfWork = httpContextAccessor.HttpContext.RequestServices.GetService<IUnitOfWork>();
}
}
}


复制代码
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
 
namespace Domain
{
 public class DemoService : IDemoService
 {
  private IUnitOfWork _unitOfWork;
 
  public DemoService (IHttpContextAccessor httpContextAccessor)
  {
   _unitOfWork = httpContextAccessor.HttpContext.RequestServices.GetService<IUnitOfWork>();
  }
 }
}
复制代码

 原文地址:https://www.cnblogs.com/donchen/p/16484705.html

标签:ServiceLocator,获取,GetService,Instance,static,var,net6,public,类中
From: https://www.cnblogs.com/elsons/p/18137799

相关文章

  • openGauss Anomaly-detection-异常检测获取帮助
    获取帮助模块命令行说明:gs_dbmindcomponentanomaly_detection--help显示如下帮助信息:usage:anomaly_detection.py[-h]--action{overview,plot}-cCONF-mMETRIC-sSTART_TIME-eEND_TIME[-HHOST][-aANOMALY]WorkloadAnomalyd......
  • openGauss Anomaly-analysis-获取帮助
    获取帮助模块命令行说明:gs_dbmindcomponentanomaly_detection--help显示如下帮助信息:usage:anomaly_analysis.py[-h]-cCONF-mMETRIC-sSTART_TIME-eEND_TIME-HHOST[--csv-dump-pathCSV_DUMP_PATH]WorkloadAnomalyanalysis:A......
  • LayUI弹窗确定后获取子页面的值(如获取UEditor富文本的内容,或input标签内容)
    LayUI弹窗确定后获取子页面的值(如获取UEditor富文本的内容,或input标签内容)子窗体JS代码<scriptsrc="~/lib/ueditor-1.4.3.3/ueditor.config.js"></script><scriptsrc="~/lib/ueditor-1.4.3.3/ueditor.all.js"></script><script>varue=UE.......
  • 获取layui表格(table)当前页的页码值和当前页的数据条数
    获取layui表格(table)当前页的页码值和当前页的数据条数在浏览器查看源码,获取当前页面的数据条数如下核心代码$(".layui-laypage-limits").find("option:selected").val()//分页数目$(".layui-laypage-skip").find("input").val()//当前页码值//转载请保留原创地址http:......
  • js获取元素位置
    js获取元素位置JavaScript中获取元素位置的方法有以下几种实现方式: 使用getBoundingClientRect()方法:constelement=document.getElementById('elementId');constrect=element.getBoundingClientRect();constposition={top:rect.top,lef......
  • js获取时间差,返回格式为01天02小时03秒
    //获取时间差返回值格式:01天02小时30秒exportfunctioncaclulateDiffTime(start,end):string{start=newDate(start).getTime();end=newDate(end).getTime();letstaytimeGap=end-start;if(staytimeGap<0){staytimeGap=start-end;}i......
  • iframe跨域,获取iframe中元素
    1.需求让iframe嵌入页面,并且没有滚动条,也就是相当于两个页面拼接在一起跨域解决,通过框架配置代理proxy:{'/medical':{target:'https://example.com',changeOrigin:true,pathRewrite:{'^/medical':'',},},}......
  • Java调用第三方接口获取数据并存储,思路加代码
    思路:1.根据第三方接口返回的字段来创建实体类,用来接收数据2.建立连接,提供两种方式。来获取数据3.实体类转换并存储方法一:URL建立连接进行接收数据依赖<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifa......
  • 从Google网页中通过正则表达式获取json如何转换unicode对象
    场景:Google爬虫,获取下拉框搜索关键词,需要获取页面的里面的json字符串如下面:'{\\x22aa\\x22:{},\\x22abd\\x22:{\\x22abd\\x22:false,\\x22deb\\x22:false,\\x22det\\x22:false},\\x22async\\x22:{},\\x22attn\\x22:{},\\x22bgd\\x22:{\\x22ac\\x22:true,\\x......
  • Ant - Form 自定义组件 form.getFiledsValue 如何获取值
    import{FC,useState}from'react';importtype{SelectProps}from'antd';import{Select,Space,Flex,Input,Button}from'antd';/***扩展选择器组件,可以通过键盘enter输入一个Option*/constInputSelect:FC<{defaultOptio......