//注册ReZero.Api
builder.Services.AddReZeroServices(api =>
{
var apiObj = SuperAPIOptions.GetOptions("rezero.json");
//获取IOC需要的DLL
var assemblyList = Assembly
.GetExecutingAssembly()
//根据dll命过滤出需要的
.GetAllDependentAssemblies(it => it.Contains("MyProject"))
.ToArray();
apiObj!.DependencyInjectionOptions = new DependencyInjectionOptions(assemblyList);
api.EnableSuperApi(apiObj);
});同上下文:IScopeContract
单例:ISingletonContract
瞬时: ITransientContract
//继承就可以自动注入
public class MyService : IScopeContract //业务一般推荐 IScopeContract
{
public int CalculateSum(int num, int num2)
{
return num2 + num;
}
}
//接口看下面接口也可以自动注入
public class Class1:IClass1, IScopeContract
{
public string? a { get; set; } = "a";
}
public interface IClass1
{
} private Class2 Class2;
public WeatherForecastController(Class2 class2)
{
this.Class2=class2;
}//属性注入只支持 API类,其他的用构造函数
[DI]
public Class2? class2 { get; set; }//根据上下文获取对象,不能用于定时任务
//支持API事务
DependencyResolver.GetHttpContextRequiredService<Class2>();
//每次都是新对象(可以用定时任或者开线程)
DependencyResolver.GetNewRequiredService<Class2>()
//new出新对象下面都用这个对象 (可用于定时任务中的事务)
using (var scope = DependencyResolver.Provider.CreateScope())
{
var a = scope.ServiceProvider.GetRequiredService<A>();
var b = scope.ServiceProvider.GetRequiredService<B>();
//需要using
// 你的业务逻辑
}只能是API接口,不能是定是定时任务,定时任务是没有httpContext的
//ioc获取
public Class1(IHttpContextAccessor accessor)
{
this.httpContext=accessor.HttpContext
}
//方法中获取
var httpContext = DependencyResolver.GetService<IHttpContextAccessor>().HttpContext;
//根据上下文对象获取IOC对象
var class2=DependencyResolver.GetHttpContextRequiredService<Class2>();2016 © donet5.comApache Licence 2.0