ABP使用AutoFac自动依赖注入,以及手动扩展AutoFac实现批量依赖注入

1、替换默认容器

1.1、引入Autofac包

//引入Volo.Abp.Autofac包,选择与.net core一致的版本
Volo.Abp.Autofac

1.2、在program中调用UseAutofac()

builder.Host.UseAutofac(); // 启用Autofac容器 

1.3、在Module中DependsOn AbpAutofacModule

[DependsOn(typeof(AbpAutofacModule))]

2、自动服务注册(ApplicationService实现了ITransientDependency,继承ApplicationService就会将服务注入容器)

//接口实现以下三种接口,ABP会自动将其注册到容器,生命周期取决于接口类型,这三个接口仅仅起到只是用来标记可以被添加到IOC容器的作用
//瞬时
ITransientDependency
//单例
ISingletonDependency
//作用域
IScopedDependency

3、模块化注册

3.1、通过ABP的模块系统AbpModule手动注册:在模块的ConfigureServices方法中使用ContainerBuilder直接注册服务。

//以瞬时为例
public override void ConfigureServices(ServiceConfigurationContext context)
{
    context.Services.AddTransient<IMyService, MyService>();
}

3.2、通过ABP的模块系统AbpModule批量注册:使用Assembly扫描。

 public override void ConfigureServices(ServiceConfigurationContext context)
 {
     var scanningAssembly = typeof(YourAppApplicationModule).Assembly; // 指定包含类的程序集
     context.Services.AddAutofacScan(scan => scan
     .FromAssemblies(scanningAssembly) // 从程序集扫描
     .AddCustomAnnotations() // 添加自定义特性,如果有的话
     .AsClosedTypesOf(typeof(IYourService<>)) // 作为关闭类型的接口注册,例如IYourService<T>
     .AsSelf() // 注册为自身类型
     .WithParameter((p, d) => p.Name == "Dependency" && p.ParameterType == typeof(string), "Value") // 添加参数(可选)
      );
 }
//使用RegisterAssemblyByConvention方法直接地控制注册过程
public override void ConfigureServices(ServiceConfigurationContext context)
{
      var builder = new ContainerBuilder();
      builder.RegisterAssemblyTypes(typeof(YourAppApplicationModule).Assembly) // 指定程序集
      .AsImplementedInterfaces() // 作为实现接口注册
      .InstancePerLifetimeScope(); // 生命周期设置为每个请求范围(或根据需要选择其他生命周期)
      context.Services.UseAutofac(builder); // 使用Autofac容器构建器配置服务容器
}
posted @ 2025-04-28 19:20  是铭不是明  阅读(133)  评论(0)    收藏  举报