public class AppService { public static IServiceCollection Services { get; set; } }
using WebApplication4; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //只看这2行代码就行了,.NET 34567 可能大同小异步 builder.Services.AddHttpContextAccessor(); AppService.Services = builder.Services; var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
//如果要获取Scope对象(代码位置程序启动) //1:注入HttpContextAccessor services.AddHttpContextAccessor(); //2:获取对象(代码位置API请求里面,不是HTTP请求里面获不到HTTP对象的) ISqlSugarClient db=AppService.Services.BuildServiceProvider() .GetService<IHttpContextAccessor>() .HttpContext.RequestServices.GetService<ISqlSugarClient>()//xxx需要注册IOC
Furion框架等有现成的方法,不需要自已封装,可以上手就用。
App.GetService<XX>()
2016 © donet5.comApache Licence 2.0