IOC

1、配置依赖dll

//注册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);

});

2、自动注册IOC 

同上下文:IScopeContract 

单例:ISingletonContract

瞬时: ITransientContract

2.1 类自动注册

//继承就可以自动注入 
public class MyService : IScopeContract //业务一般推荐 IScopeContract 
{
   public int CalculateSum(int num, int num2)
   {
        return num2 + num;
    }
}
//接口看下面

2.2 接口自动注册

接口也可以自动注入

public class Class1:IClass1, IScopeContract
{
  public string? a { get; set; } = "a";
}
     
public interface IClass1
{
}

3、IOC获取对象方式

3.1  构造函数获取

 private Class2 Class2;
 public WeatherForecastController(Class2 class2) 
 {
     this.Class2=class2;
 }

3.2  属性注入

//属性注入只支持 API类,其他的用构造函数
[DI]
public Class2? class2 { get; set; }

3.3 方法内获取IOC

//根据上下文获取对象,不能用于定时任务
//支持API事务
DependencyResolver.GetHttpContextRequiredService<Class2>();

//每次都是新对象(可以用定时任或者开线程)
DependencyResolver.GetNewRequiredService<Class2>()

//new出新对象下面都用这个对象 (可用于定时任务中的事务)
var scope=DependencyResolver.Provider.CreateScope().ServiceProvider;
var a=scope.GetRequiredService<A>();
var b=scope.GetRequiredService<B>();

4、获取httpContext

只能是API接口,不能是定是定时任务,定时任务是没有httpContext的

//ioc获取
public Class1(IHttpContextAccessor accessor) 
{
   this.httpContext=accessor.HttpContext
}

//方法中获取
var httpContext = DependencyResolver.GetService<IHttpContextAccessor>().HttpContext;

//根据上下文对象获取IOC对象
var class2=DependencyResolver.GetHttpContextRequiredService<Class2>();


果糖网