翼度科技»论坛 编程开发 .net 查看内容

Abp vNext 依赖注入

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
文章目录
介绍

ABP的依赖注入系统是基于Microsoft的依赖注入扩展库(Microsoft.Extensions.DependencyInjection nuget包)开发的。所以我们采用dotnet自带的注入方式也是支持的

  • 由于ABP是一个模块化框架,因此每个模块都定义它自己的服务并在它自己的单独模块类中通过依赖注入进行注册.例:
  1. public class BlogModule : AbpModule
  2. {
  3.     public override void ConfigureServices(ServiceConfigurationContext context)
  4.     {
  5.         //在此处注入依赖项
  6.         // dotnet自带依赖注入方式也是支持的
  7.         context.services.AddTransient
  8.         context.services.AddScoped
  9.         context.services.AddSingleton
  10.     }
  11. }
复制代码
Autofac

Autofac 是.Net世界中最常用的依赖注入框架之一. 相比.Net Core标准的依赖注入库, 它提供了更多高级特性, 比如动态代理和属性注入.
集成

1.安装 Volo.Abp.Autofac nuget 包到你的项目 (对于一个多项目应用程序, 建议安装到可执行项目或者Web项目中.)
2.模块添加 AbpAutofacModule 依赖:
  1.     [DependsOn(typeof(AbpAutofacModule))]
  2.     public class MyModule : AbpModule
  3.     {
  4.         //...
  5.     }
  6. }
复制代码
3.配置 AbpApplicationCreationOptions 用 Autofac 替换默认的依赖注入服务. 根据应用程序类型, 情况有所不同

  • ASP.NET Core 应用程序
  1. public class Program
  2. {
  3.     public static int Main(string[] args)
  4.     {
  5.         CreateHostBuilder(args).Build().Run();
  6.     }
  7.     internal static IHostBuilder CreateHostBuilder(string[] args) =>
  8.         Host.CreateDefaultBuilder(args)
  9.             .ConfigureWebHostDefaults(webBuilder =>
  10.             {
  11.                 webBuilder.UseStartup<Startup>();
  12.             })
  13.             .UseAutofac(); //Integrate Autofac!
  14. }
复制代码

  • 控制台应用程序
  1. namespace AbpConsoleDemo
  2. {
  3.     class Program
  4.     {
  5.         static void Main(string[] args)
  6.         {
  7.             using (var application = AbpApplicationFactory.Create<AppModule>(options =>
  8.             {
  9.                 options.UseAutofac(); //Autofac integration
  10.             }))
  11.             {
  12.                 //...
  13.             }
  14.         }
  15.     }
  16. }
复制代码
依照约定的注册

如果实现这些接口,则会自动将类注册到依赖注入:

  • ITransientDependency 注册为transient生命周期.
  • ISingletonDependency 注册为singleton生命周期.
  • IScopedDependency 注册为scoped生命周期.
默认特定类型

一些特定类型会默认注册到依赖注入.例子:

  • 模块类注册为singleton.
  • MVC控制器(继承Controller或AbpController)被注册为transient.
  • MVC页面模型(继承PageModel或AbpPageModel)被注册为transient.
  • MVC视图组件(继承ViewComponent或AbpViewComponent)被注册为transient.
  • 应用程序服务(实现IApplicationService接口或继承ApplicationService类)注册为transient.
  • 存储库(实现IRepository接口)注册为transient.
  • 域服务(实现IDomainService接口)注册为transient.
手动注册

在某些情况下,你可能需要向IServiceCollection手动注册服务,尤其是在需要使用自定义工厂方法或singleton实例时.在这种情况下,你可以像Microsoft文档描述的那样直接添加服务.
  1. public class BlogModule : AbpModule
  2. {
  3.     public override void ConfigureServices(ServiceConfigurationContext context)
  4.     {
  5.         context.services.AddTransient<ITestMicrosoftManager, TestMicrosoftManager>();
  6.     }
  7. }
复制代码
如何使用

构造函数注入


  • 构造方法注入是将依赖项注入类的首选方式
属性注入


  • Microsoft依赖注入库不支持属性注入.但是,ABP可以与第三方DI提供商(例如Autofac)集成,以实现属性注入。
  • 属性注入依赖项通常被视为可选依赖项.这意味着没有它们,服务也可以正常工作.Logger就是这样的依赖项,MyService可以继续工作而无需日志记录.
  1. public class MyService : ITransientDependency
  2. {
  3.     public ILogger<MyService> Logger { get; set; }
  4.     public MyService()
  5.     {
  6.         Logger = NullLogger<MyService>.Instance;
  7.     }
  8.     public void DoSomething()
  9.     {
  10.         //...使用 Logger 写日志...
  11.     }
  12. }
复制代码
IServiceProvider

直接从IServiceProvider解析服务.在这种情况下,你可以将IServiceProvider注入到你的类并使用
  1. public class MyService : ITransientDependency
  2. {
  3.     private readonly IServiceProvider _serviceProvider;
  4.     public MyService(IServiceProvider serviceProvider)
  5.     {
  6.         _serviceProvider = serviceProvider;
  7.     }
  8.     public void DoSomething()
  9.     {
  10.         var taxCalculator = _serviceProvider.GetService<ITaxCalculator>();
  11.         //...
  12.     }
  13. }
复制代码
服务替换

在某些情况下,需要替换某些接口的实现.

  • ITestManager有一个默认实现DefaultManager,但是我现在想替换成TestReplaceManager,该如何操作呢?
原生dotnet方式替换
  1. services.Replace(ServiceDescriptor.Transient<ITestManager, TestReplaceManager>());
复制代码
Abp支持


  • 加上Dependency特性标签
  • 加上ExposeServices特性标签
  1. [Dependency(ReplaceServices = true)]
  2. [ExposeServices(typeof(ITestManager))]
  3. public class TestReplaceManager : ITestManager, ITransientDependency
  4. {
  5.         public void Print()
  6.         {
  7.                 Console.WriteLine("TestReplaceManager");
  8.         }
  9. }
复制代码
问题


  • 有时候我们实现了ITransientDependency,ISingletonDependency,IScopedDependency但是再运行是还是提示依赖注入失败?


  • 实现类的名称拼写错误
  • 比如接口名称为ITestAppService,但是实现类为DefaultTessAppService,这个时候编译不会报错,但是运行报错,下面会基于源码分析。
  1. public class DefaultTessAppService : ApplicationService, ITestAppService
  2. {
  3.    // ....
  4. }
复制代码

  • 我通过[Dependency(ReplaceServices = true)]替换服务没有生效?


  • 请添加[ExposeServices(typeof(ITestManager))]显示暴露服务,下面会基于源码分析。
源码分析


  • 进入到Startup.AddApplication源码
  1. public class Startup
  2. {
  3.     public void ConfigureServices(IServiceCollection services)
  4.     {
  5.         services.AddApplication<xxxManagementHttpApiHostModule>();
  6.     }
  7. }
复制代码

  • 进入到await app.ConfigureServicesAsync()源码
  1. public async static Task<IAbpApplicationWithExternalServiceProvider> CreateAsync(
  2.     [NotNull] Type startupModuleType,
  3.     [NotNull] IServiceCollection services,
  4.     Action<AbpApplicationCreationOptions>? optionsAction = null)
  5. {
  6.     var app = new AbpApplicationWithExternalServiceProvider(startupModuleType, services, options =>
  7.     {
  8.         options.SkipConfigureServices = true;
  9.         optionsAction?.Invoke(options);
  10.     });
  11.     await app.ConfigureServicesAsync();
  12.     return app;
  13. }
复制代码

  • 主要查看ConfigureServices下的Services.AddAssembly(assembly)方法。
  1. public virtual async Task ConfigureServicesAsync()
  2.     {
  3.         
  4.         // 省略...
  5.         var assemblies = new HashSet<Assembly>();
  6.         //ConfigureServices
  7.         foreach (var module in Modules)
  8.         {
  9.             if (module.Instance is AbpModule abpModule)
  10.             {
  11.                 if (!abpModule.SkipAutoServiceRegistration)
  12.                 {
  13.                     var assembly = module.Type.Assembly;
  14.                     if (!assemblies.Contains(assembly))
  15.                     {
  16.                         Services.AddAssembly(assembly);
  17.                         assemblies.Add(assembly);
  18.                     }
  19.                 }
  20.             }
  21.             try
  22.             {
  23.                 await module.Instance.ConfigureServicesAsync(context);
  24.             }
  25.             catch (Exception ex)
  26.             {
  27.                 throw new AbpInitializationException($"An error occurred during {nameof(IAbpModule.ConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex);
  28.             }
  29.         }
  30.         // 省略...
  31.     }
复制代码
4.进入下面AddAssembly下AddType的逻辑
  1. public class DefaultConventionalRegistrar : ConventionalRegistrarBase
  2. {
  3.     public override void AddType(IServiceCollection services, Type type)
  4.     {
  5.         if (IsConventionalRegistrationDisabled(type))
  6.         {
  7.             return;
  8.         }
  9.         // 查看是否有DependencyAttribute特性标签
  10.         var dependencyAttribute = GetDependencyAttributeOrNull(type);
  11.         // 判断是否有实现接口,注入对于的类型。
  12.         var lifeTime = GetLifeTimeOrNull(type, dependencyAttribute);
  13.         if (lifeTime == null)
  14.         {
  15.             return;
  16.         }
  17.         var exposedServiceTypes = GetExposedServiceTypes(type);
  18.         TriggerServiceExposing(services, type, exposedServiceTypes);
  19.         foreach (var exposedServiceType in exposedServiceTypes)
  20.         {
  21.             var serviceDescriptor = CreateServiceDescriptor(
  22.                 type,
  23.                 exposedServiceType,
  24.                 exposedServiceTypes,
  25.                 lifeTime.Value
  26.             );
  27.             if (dependencyAttribute?.ReplaceServices == true)
  28.             {
  29.                 services.Replace(serviceDescriptor);
  30.             }
  31.             else if (dependencyAttribute?.TryRegister == true)
  32.             {
  33.                 services.TryAdd(serviceDescriptor);
  34.             }
  35.             else
  36.             {
  37.                 services.Add(serviceDescriptor);
  38.             }
  39.         }
  40.     }
  41. }
  42.     // GetLifeTimeOrNull
  43.     protected virtual ServiceLifetime? GetLifeTimeOrNull(Type type, DependencyAttribute? dependencyAttribute)
  44.     {
  45.         return dependencyAttribute?.Lifetime ?? GetServiceLifetimeFromClassHierarchy(type) ?? GetDefaultLifeTimeOrNull(type);
  46.     }
  47.     // abp 三个生命周期
  48.     protected virtual ServiceLifetime? GetServiceLifetimeFromClassHierarchy(Type type)
  49.     {
  50.         if (typeof(ITransientDependency).GetTypeInfo().IsAssignableFrom(type))
  51.         {
  52.             return ServiceLifetime.Transient;
  53.         }
  54.         if (typeof(ISingletonDependency).GetTypeInfo().IsAssignableFrom(type))
  55.         {
  56.             return ServiceLifetime.Singleton;
  57.         }
  58.         if (typeof(IScopedDependency).GetTypeInfo().IsAssignableFrom(type))
  59.         {
  60.             return ServiceLifetime.Scoped;
  61.         }
  62.         return null;
  63.     }
复制代码
5.重点到了,看下为什么名称错误为什么导致注入失败。

  • 通过接口的名称去获取实现。
  • 也能解释有时候不显示指定ExposeServices可能替换失败的问题
  1. public class ExposeServicesAttribute : Attribute, IExposedServiceTypesProvider
  2. {
  3.     // 省略...
  4.     private static List<Type> GetDefaultServices(Type type)
  5.     {
  6.         var serviceTypes = new List<Type>();
  7.         foreach (var interfaceType in type.GetTypeInfo().GetInterfaces())
  8.         {
  9.             var interfaceName = interfaceType.Name;
  10.             if (interfaceType.IsGenericType)
  11.             {
  12.                 interfaceName = interfaceType.Name.Left(interfaceType.Name.IndexOf('`'));
  13.             }
  14.             // 查询到实现类的名称是否是移除I
  15.             if (interfaceName.StartsWith("I"))
  16.             {
  17.                 interfaceName = interfaceName.Right(interfaceName.Length - 1);
  18.             }
  19.             // 查询到实现类的名称是否以接口名结尾
  20.             if (type.Name.EndsWith(interfaceName))
  21.             {
  22.                 serviceTypes.Add(interfaceType);
  23.             }
  24.         }
  25.         return serviceTypes;
  26.     }
  27. }
复制代码
Abp vNext Pro

如果觉得可以,不要吝啬你的小星星哦

文章目录

来源:https://www.cnblogs.com/WangJunZzz/archive/2023/09/26/17729743.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具