Blame view

netcore/src/Infrastructure/NCC/Mapper/Extensions/MapperServiceCollectionExtensions.cs 1.42 KB
de2bd2f9   “wangming”   项目初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  using NCC;
  using NCC.Dependency;
  using NCC.Reflection;
  using System.Linq;
  using System.Reflection;
  
  namespace Microsoft.Extensions.DependencyInjection
  {
      /// <summary>
      /// 映射拓展类
      /// </summary>
      [SuppressSniffer]
      public static class MapperServiceCollectionExtensions
      {
          /// <summary>
          /// 添加对象映射
          /// </summary>
          /// <param name="services">服务集合</param>
          /// <returns></returns>
          public static IServiceCollection AddObjectMapper(this IServiceCollection services)
          {
              // 判断是否安装了 Mapster 程序集
              var mapperAssembly = App.Assemblies.FirstOrDefault(u => u.GetName().Name.Equals("NCC.Mapster"));
              if (mapperAssembly != null)
              {
                  // 加载 Mapper 拓展类型和拓展方法
                  var objectMapperServiceCollectionExtensionsType = Reflect.GetType(mapperAssembly, $"Microsoft.Extensions.DependencyInjection.ObjectMapperServiceCollectionExtensions");
                  var addObjectMapperMethod = objectMapperServiceCollectionExtensionsType
                      .GetMethods(BindingFlags.Public | BindingFlags.Static)
                      .First(u => u.Name == "AddObjectMapper");
  
                  return addObjectMapperMethod.Invoke(null, new object[] { services, App.Assemblies.ToArray() }) as IServiceCollection;
              }
  
              return services;
          }
      }
  }