ServiceModule.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using Autofac;
  2. using Autofac.Extras.DynamicProxy;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Module = Autofac.Module;
  8. using Microsoft.Extensions.DependencyModel;
  9. using ZhonTai.Admin.Core.Configs;
  10. using ZhonTai.Admin.Core.Db.Transaction;
  11. namespace ZhonTai.Admin.Core.RegisterModules;
  12. public class ServiceModule : Module
  13. {
  14. private readonly AppConfig _appConfig;
  15. /// <summary>
  16. /// 服务注入
  17. /// </summary>
  18. /// <param name="appConfig">AppConfig</param>
  19. public ServiceModule(AppConfig appConfig)
  20. {
  21. _appConfig = appConfig;
  22. }
  23. protected override void Load(ContainerBuilder builder)
  24. {
  25. //事务拦截
  26. var interceptorServiceTypes = new List<Type>();
  27. if (_appConfig.Aop.Transaction)
  28. {
  29. builder.RegisterType<TransactionInterceptor>();
  30. builder.RegisterType<TransactionAsyncInterceptor>();
  31. interceptorServiceTypes.Add(typeof(TransactionInterceptor));
  32. }
  33. if(_appConfig.AssemblyNames?.Length > 0)
  34. {
  35. //服务
  36. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  37. .Where(a => _appConfig.AssemblyNames.Contains(a.Name))
  38. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  39. //服务接口实例
  40. builder.RegisterAssemblyTypes(assemblies)
  41. .Where(a => a.Name.EndsWith("Service"))
  42. .AsImplementedInterfaces()
  43. .InstancePerLifetimeScope()
  44. .PropertiesAutowired()// 属性注入
  45. .InterceptedBy(interceptorServiceTypes.ToArray())
  46. .EnableInterfaceInterceptors();
  47. //服务实例
  48. builder.RegisterAssemblyTypes(assemblies)
  49. .Where(a => a.Name.EndsWith("Service"))
  50. .InstancePerLifetimeScope()
  51. .PropertiesAutowired()// 属性注入
  52. .InterceptedBy(interceptorServiceTypes.ToArray())
  53. .EnableClassInterceptors();
  54. }
  55. }
  56. }