经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
aspnetcore插件开发dll热加载 二
来源:cnblogs  作者:星仔007  时间:2024/5/27 9:21:33  对本文有异议

这一篇文章应该是个总结。

投简历的时候是不是有人问我有没有abp的开发经历,汗颜!

在各位大神的尝试及自己的总结下,还是实现了业务和主机服务分离,通过dll动态的加载卸载,控制器动态的删除添加。

项目如下:

 

演示效果:

 

下面就是代码部分:

重点

1.IActionDescriptorChangeProvider接口,(关于添加删除可以通过后台任务检测刷新,移除控制器操作)

2.builder.Services.AddControllers().ConfigureApplicationPartManager和AssemblyLoadContext搭配加载业务的dll(动态链接库)。

我的业务代码很简单,可能有人要说了,那复杂的业务,有很多业务类,注入这块怎么办,怎么实现整个的调用链。

关于业务和主服务之间的关联代码就在这了

  1. namespace ModuleLib
  2. {
  3. //可以给个抽象类,默认实现。否则各个服务每次实现接口会多做一步删除为实现接口的动作
  4. public interface IModule
  5. {
  6. void ConfigureService(IServiceCollection services, IConfiguration configuration=null);
  7. void Configure(IApplicationBuilder app, IWebHostEnvironment env = null);
  8. }
  9. }

 

看下面的项目,有没有一点模块化开发的感觉,但是这次分离的很彻底,只需要dll就行,不需要程序集引用。

  1. {
  2. "Modules": [
  3. {
  4. "id": "FirstWeb",
  5. "version": "1.0.0",
  6. "path": "C:\\Users\\victor.liu\\Documents\\GitHub\\AspNetCoreSimpleAop\\LastModule\\FirstWeb\\bin\\Debug\\net8.0"
  7. },
  8. {
  9. "id": "SecondService",
  10. "version": "1.0.0",
  11. "path": "C:\\Users\\victor.liu\\Documents\\GitHub\\AspNetCoreSimpleAop\\LastModule\\SecondService\\bin\\Debug\\net8.0" //????csproj?????????????з???????????????????????????
  12. }
  13. ]
  14. }

以Assembly为单位做存储

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Common
  8. {
  9. public class ModuleInfo
  10. {
  11. public string Id { get; set; }
  12. public string Name { get; set; }
  13. public Version Version { get; set; }
  14. public string Path { get; set; } = "lib";
  15. public Assembly Assembly { get; set; }
  16. }
  17. }

在初次加载的时候注入Imodule,并且缓存起来,这样避免了反射的操作,之前的做法是通过反射来拿IModule

  1. using Common;
  2. using ModuleLib;
  3. using System.Reflection;
  4. namespace MainHost.ServiceExtensions
  5. {
  6. public static class InitModuleExt
  7. {
  8. public static void InitModule(this IServiceCollection services,IConfiguration configuration)
  9. {
  10. var modules = configuration.GetSection("Modules").Get<List<ModuleInfo>>();
  11. foreach (var module in modules)
  12. {
  13. GolbalConfiguration.Modules.Add(module);
  14. module.Assembly = Assembly.LoadFrom($"{module.Path}\\{module.Id}.dll"); //测试才这么写
  15.  
  16. var moduleType = module.Assembly.GetTypes().FirstOrDefault(t => typeof(IModule).IsAssignableFrom(t));
  17. if ((moduleType != null) && (moduleType != typeof(IModule)))
  18. {
  19. services.AddSingleton(typeof(IModule), moduleType);
  20. }
  21. }
  22. }
  23. }
  24. }

 

再看看Program是怎么写的,等等,为什么注释掉了重要的代码呢

  1. using BigHost;
  2. using BigHost.AssemblyExtensions;
  3. using Common;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.AspNetCore.Mvc.ApplicationParts;
  6. using Microsoft.AspNetCore.Mvc.Infrastructure;
  7. using Microsoft.Extensions.Configuration;
  8. using ModuleLib;
  9. using System.Xml.Linq;
  10. using DependencyInjectionAttribute;
  11. var builder = WebApplication.CreateBuilder(args);
  12. builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
  13. builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
  14. builder.Configuration.AddJsonFile("appsettings.Modules.json", optional: false, reloadOnChange: true);
  15. //builder.Services.InitModule(builder.Configuration);
  16. //var sp = builder.Services.BuildServiceProvider();
  17. //var modules = sp.GetServices<IModule>();
  18. // Add services to the container.
  19. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  20. builder.Services.AddEndpointsApiExplorer();
  21. builder.Services.AddSwaggerGen();
  22. //最新dotnet没有这些
  23. builder.Services.AddControllers().ConfigureApplicationPartManager(apm =>
  24. {
  25. var context = new CollectibleAssemblyLoadContext();
  26. DirectoryInfo DirInfo = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "lib"));
  27. foreach (var file in DirInfo.GetFiles("*.dll"))
  28. {
  29. //if(!(file.Name.Contains("Test001Controller") || file.Name.Contains("Test002Controller")))
  30. //{
  31. // continue;
  32. //}//不能屏蔽掉依赖引用
  33. var assembly = context.LoadFromAssemblyPath(file.FullName);
  34. var controllerAssemblyPart = new AssemblyPart(assembly);
  35. apm.ApplicationParts.Add(controllerAssemblyPart);
  36. ExternalContexts.Add(file.Name, context);
  37. }
  38. });
  39. //builder.Services.AddTransient<IProductBusiness, ProductBusiness>();
  40. //foreach (var module in modules)
  41. //{
  42. // module.ConfigureService(builder.Services, builder.Configuration);
  43. //}
  44. //GolbalConfiguration.Modules.Select(x => x.Assembly).ToList().ForEach(x =>
  45. //{
  46. // builder.Services.ReisterServiceFromAssembly(x);
  47. // var controllerAssemblyPart = new AssemblyPart(x);
  48. // apm.ApplicationParts.Add(controllerAssemblyPart);
  49. // ExternalContexts.Add(x.GetName().Name, context);
  50. //});
  51. //});
  52. //GolbalConfiguration.Modules.Select(x => x.Assembly).ToList().ForEach(x => builder.Services.ReisterServiceFromAssembly(x));
  53. builder.Services.AddSingleton<IActionDescriptorChangeProvider>(ActionDescriptorChangeProvider.Instance);
  54. builder.Services.AddSingleton(ActionDescriptorChangeProvider.Instance);
  55. var app = builder.Build();
  56. ServiceLocator.Instance = app.Services;
  57. //foreach (var module in modules)
  58. //{
  59. // module.Configure(app, app.Environment);
  60. //}
  61. // Configure the HTTP request pipeline.
  62. if (app.Environment.IsDevelopment())
  63. {
  64. app.UseSwagger();
  65. app.UseSwaggerUI();
  66. }
  67. app.UseHttpsRedirection();
  68. app.MapGet("/Add", ([FromServices] ApplicationPartManager _partManager, string name) =>
  69. {
  70. FileInfo FileInfo = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "lib/" + name + ".dll"));
  71. using (FileStream fs = new FileStream(FileInfo.FullName, FileMode.Open))
  72. {
  73. var context = new CollectibleAssemblyLoadContext();
  74. var assembly = context.LoadFromStream(fs);
  75. var controllerAssemblyPart = new AssemblyPart(assembly);
  76. _partManager.ApplicationParts.Add(controllerAssemblyPart);
  77. //ExternalContexts.Add(name + ".dll", context);
  78. ExternalContexts.Add(name, context);
  79. //更新Controllers
  80. ActionDescriptorChangeProvider.Instance.HasChanged = true;
  81. ActionDescriptorChangeProvider.Instance.TokenSource!.Cancel();
  82. }
  83. return "添加{name}controller成功";
  84. })
  85. .WithTags("Main")
  86. .WithOpenApi();
  87. app.MapGet("/Remove", ([FromServices] ApplicationPartManager _partManager, string name) =>
  88. {
  89. //if (ExternalContexts.Any(
  90. // $"{name}.dll"))
  91. if (ExternalContexts.Any(
  92. $"{name}"))
  93. {
  94. var matcheditem = _partManager.ApplicationParts.FirstOrDefault(x => x.Name == name);
  95. if (matcheditem != null)
  96. {
  97. _partManager.ApplicationParts.Remove(matcheditem);
  98. matcheditem = null;
  99. }
  100. ActionDescriptorChangeProvider.Instance.HasChanged = true;
  101. ActionDescriptorChangeProvider.Instance.TokenSource!.Cancel();
  102. //ExternalContexts.Remove(name + ".dll");
  103. ExternalContexts.Remove(name);
  104. return $"成功移除{name}controller";
  105. }
  106. else
  107. {
  108. return "$没有{name}controller";
  109. }
  110. });
  111. app.UseRouting(); //最新dotnet没有这些
  112. app.MapControllers(); //最新dotnet没有这些
  113. app.Run();

 

这里先对上面的尝试做个总结:

模块化开发通过IModule分离各个模块解耦,通过dll把接口加入到主程序,很nice,但是,我还想更深入一层,把这个接口也一并做成可拔可插,这样就不得不考虑如何动态的重载controller,这也没问题。重中之重来了,上面的都做到了,但是我要的不仅仅是增加删除一个controller,关联的业务代码发生了改变如何重载刷新,依赖注入这一块绕不过去。并没有好的解决办法,就这样项目戛然而止。

目前有两种解决办法:

1.加个中间层,通过反射去动态获取业务实现

2.业务实现通过new对象来拿。

下面是代码:

  1. using IOrder.Repository;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using System.Reflection;
  9. using System.Runtime.Loader;
  10. namespace AutofacRegister
  11. {
  12. public interface IRepositoryProvider
  13. {
  14. IRepository GetRepository(string serviceeName);
  15. }
  16. public class RepositoryProvider : IRepositoryProvider
  17. {
  18. private readonly Dictionary<string, (Assembly assembly, DateTime lastModified)> _assemblyCache = new Dictionary<string, (Assembly assembly, DateTime lastModified)>();
  19. private readonly Dictionary<string, IRepository> _typeCache = new Dictionary<string, IRepository>();
  20. public IRepository GetRepository(string serviceName)
  21. {
  22. var path = $"{Directory.GetCurrentDirectory()}\\lib\\{serviceName}.Repository.dll";
  23. var lastModified = File.GetLastWriteTimeUtc(path);
  24. if (_assemblyCache.TryGetValue(path, out var cachedEntry) && cachedEntry.lastModified == lastModified)
  25. {
  26. // 使用缓存中的 Assembly 对象
  27. return CreateInstanceFromAssembly(cachedEntry.assembly,serviceName);
  28. }
  29. else
  30. {
  31. // 加载并缓存新的 Assembly 对象
  32. var assembly = LoadAssemblyFromFile(path);
  33. _assemblyCache[path] = (assembly, lastModified);
  34. return CreateInstanceFromAssembly(assembly,serviceName);
  35. }
  36. }
  37. private Assembly LoadAssemblyFromFile(string path)
  38. {
  39. var _AssemblyLoadContext = new AssemblyLoadContext(Guid.NewGuid().ToString("N"), true);
  40. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
  41. {
  42. return _AssemblyLoadContext.LoadFromStream(fs);
  43. }
  44. }
  45. private IRepository CreateInstanceFromAssembly(Assembly assembly,string serviceName)
  46. {
  47. var type_key = $"{assembly.FullName}_{serviceName}";
  48. if(_typeCache.TryGetValue(type_key, out var cachedType))
  49. {
  50. return _typeCache[type_key];
  51. }
  52. var type = assembly.GetTypes()
  53. .Where(t => typeof(IRepository).IsAssignableFrom(t) && !t.IsInterface)
  54. .FirstOrDefault();
  55. if (type != null)
  56. {
  57. var instance= (IRepository)Activator.CreateInstance(type);
  58. _typeCache[type_key] = instance;
  59. return instance;
  60. }
  61. else
  62. {
  63. throw new InvalidOperationException("No suitable type found in the assembly.");
  64. }
  65. }
  66. }
  67. }

 

所有的注入业务放到单独的注入文件中,

  1. using Autofac;
  2. using IOrder.Repository;
  3. using Order.Repository;
  4. namespace AutofacRegister
  5. {
  6. public class RepositoryModule:Module
  7. {
  8. protected override void Load(ContainerBuilder builder)
  9. {
  10. //builder.RegisterType<Repository>().As<IRepository>().SingleInstance();
  11. builder.RegisterType<RepositoryProvider>().As<IRepositoryProvider>().InstancePerLifetimeScope();
  12. }
  13. }
  14. }

 

上面的代码可以再加一层代理,类似这样

  1. using CustomAttribute;
  2. using System.Reflection;
  3. using ZURU_ERP.Base.Common.UnitOfWork;
  4. using ZURU_ERP.Base.Common;
  5. using ZURU_ERP.Base.Model;
  6. using System.Collections.Concurrent;
  7. namespace ZURU_ERP.Base.Reflect
  8. {
  9. public class MethodInfoCache
  10. {
  11. public string Name { get; set; }
  12. public Type ClassType { get; set; }
  13. public CusTransAttribute TransAttribute { get; set; }
  14. public List<CusActionAttribute> ActionAttributes { get; set; }
  15. public bool UseTrans => (TransAttribute == null);
  16. public bool UseAop => ActionAttributes.Any();
  17. }
  18. public class CusProxyGenerator<T> : DispatchProxy where T:class
  19. {
  20. private readonly ConcurrentDictionary<string, MethodInfoCache> _cache = new ConcurrentDictionary<string, MethodInfoCache>();
  21. private IBusiness<T> business;
  22. private List<ICusAop> cusAop;
  23. protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
  24. {
  25. #region 缓存优化 未经过测试
  26. string methodKey = targetMethod.Name;
  27. if (!_cache.ContainsKey(methodKey))
  28. {
  29. var classType = business.GetType();
  30. var transAttribute = classType.GetMethod(targetMethod.Name).GetCustomAttributes<CusTransAttribute>().FirstOrDefault();
  31. var actionAttributes = classType.GetMethod(targetMethod.Name).GetCustomAttributes<CusActionAttribute>().ToList();
  32. _cache[methodKey] = new MethodInfoCache()
  33. {
  34. Name = methodKey,
  35. ClassType = classType,
  36. TransAttribute = transAttribute,
  37. ActionAttributes = actionAttributes
  38. };
  39. }
  40. var methodInfoCache = _cache[methodKey];
  41. object result;
  42. if (methodInfoCache.UseAop)
  43. {
  44. var actionnames = methodInfoCache.ActionAttributes.Select(x => x.Name).ToList();
  45. var waitInvokes = cusAop.Where(x => actionnames.Contains(x.GetType().Name)).OrderBy(x => actionnames.IndexOf(x.GetType().Name)).ToList(); //排序
  46. foreach (var item in waitInvokes)
  47. {
  48. item.Before(args);
  49. }
  50. result = methodInfoCache.UseTrans ? Trans(targetMethod, args, out result) : targetMethod.Invoke(business, args);
  51. foreach (var item in waitInvokes)
  52. {
  53. item.After(new object[] { result });
  54. }
  55. return result;
  56. }
  57. else
  58. {
  59. return methodInfoCache.UseTrans ? Trans(targetMethod, args, out result) : targetMethod.Invoke(business, args);
  60. }
  61. #endregion
  62.  
  63. #region 没缓存原代码 经过测试
  64.  
  65. //bool useTran = false;
  66. //var classType = business.GetType();
  67. //var useClassTrans = classType.GetCustomAttributes<CusTransAttribute>();
  68. //if (useClassTrans.Any())
  69. //{
  70. // useTran = true;
  71. //}
  72. //else
  73. //{
  74. // useTran = classType.GetMethod(targetMethod.Name).GetCustomAttributes<CusTransAttribute>().Any(); //是否使用事务
  75. //}
  76. //var actionnames = classType.GetCustomAttributes<CusActionAttribute>().Select(x => x.Name).ToList();
  77. //var waitInvokes = cusAop.Where(x => actionnames.Contains(x.GetType().Name)).OrderBy(x => actionnames.IndexOf(x.GetType().Name)).ToList(); //排序
  78. //foreach (var item in waitInvokes)
  79. //{
  80. // item.Before(args);
  81. //}
  82. //object result;
  83. //if (useTran)
  84. //{
  85. // return Trans(targetMethod, args, out result);
  86. //}
  87. //else
  88. //{
  89. // result = targetMethod.Invoke(business, args);
  90. //}
  91. //foreach (var item in waitInvokes)
  92. //{
  93. // item.After(new object[] { result });
  94. //}
  95. //return result;
  96. #endregion
  97. }
  98. private object? Trans(MethodInfo? targetMethod, object?[]? args, out object result)
  99. {
  100. var _unitOfWorkManage = App.GetService<IUnitOfWorkManage>();
  101. Console.WriteLine($"{targetMethod.Name} transaction started.");
  102. try
  103. {
  104. if (_unitOfWorkManage.TranCount <= 0)
  105. {
  106. Console.WriteLine($"Begin Transaction");
  107. _unitOfWorkManage.BeginTran();
  108. }
  109. result = targetMethod.Invoke(business, args);
  110. if (result is ApiResult apiResult && !apiResult.success)
  111. {
  112. Console.WriteLine("apiResult return false Transaction rollback.");
  113. _unitOfWorkManage.RollbackTran();
  114. return apiResult;
  115. }
  116. if (_unitOfWorkManage.TranCount > 0)
  117. _unitOfWorkManage.CommitTran();
  118. Console.WriteLine("Transaction Commit.");
  119. Console.WriteLine($"{targetMethod.Name} transaction succeeded.");
  120. return result;
  121. }
  122. catch (Exception e)
  123. {
  124. _unitOfWorkManage.RollbackTran();
  125. Console.WriteLine("Transaction Rollback.");
  126. Console.WriteLine($"{targetMethod.Name} transaction failed: " + e.Message);
  127. throw;
  128. }
  129. }
  130. public static IBusiness<T> Create(IBusiness<T> business, List<ICusAop> cusAop)
  131. {
  132. object proxy = Create<IBusiness<T>, CusProxyGenerator<T>>();
  133. ((CusProxyGenerator<T>)proxy).SetParameters(business, cusAop);
  134. return (IBusiness<T>)proxy;
  135. }
  136. private void SetParameters(IBusiness<T> business, List<ICusAop> cusAop)
  137. {
  138. this.business = business;
  139. this.cusAop = cusAop;
  140. }
  141. }
  142. }

 

由于这层代码没有走依赖注入,想用各种aop组件,灵活性稍微低了一点点。

下面第二种直接在业务代码中new对象也不是不可,这一层的前后需要的都可以注入到容器里面去。只不过这一层就想到包装类一层不要在使用这个类的时候做过多的职责承担

  1. using IBusiness;
  2. namespace Business
  3. {
  4. public class ProductBusiness : IDisposable// : IProductBusiness
  5. {
  6. public static readonly ProductBusiness Instance;
  7. private bool _disposed = false;
  8. static ProductBusiness()
  9. {
  10. Instance = new ProductBusiness();
  11. }
  12. private ProductBusiness()
  13. {
  14. // 初始化资源
  15. }
  16. public async Task<int> AddProduct(string name, decimal price)
  17. {
  18. await Task.CompletedTask;
  19. return 1;
  20. }
  21. // 实现IDisposable接口
  22. public void Dispose()
  23. {
  24. Dispose(true);
  25. GC.SuppressFinalize(this);
  26. }
  27. protected virtual void Dispose(bool disposing)
  28. {
  29. if (_disposed)
  30. return;
  31. if (disposing)
  32. {
  33. // 释放托管资源
  34. }
  35. // 释放非托管资源
  36. _disposed = true;
  37. }
  38. // 析构函数
  39. ~ProductBusiness()
  40. {
  41. Dispose(false);
  42. }
  43. }
  44. }

使用的时候就直接拿实例:

  1. [HttpPost]
  2. public async Task<int> Add()
  3. {
  4. //using var scope = ServiceLocator.Instance.CreateScope();
  5. //var business = scope.ServiceProvider.GetRequiredService<IProductBusiness>();
  6. using var business = ProductBusiness.Instance;
  7. return await business.AddProduct("product1",12.1m);
  8. }

 

demo源代码:

liuzhixin405/AspNetCoreSimpleAop (github.com)

 

原文链接:https://www.cnblogs.com/morec/p/18211276

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号