首页 > 其他分享 >使用 AotoFac 注册AutoMapper

使用 AotoFac 注册AutoMapper

时间:2022-11-22 15:25:21浏览次数:47  
标签:type System AotoFac typeof 注册 AutoMapper using assembliesToScan

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using AutoMapper;

namespace Stock.Infrastructure;
public class AutoMapperModule : Autofac.Module
{

  private readonly IEnumerable<Assembly> assembliesToScan;
  public AutoMapperModule(IEnumerable<Assembly> assembliesToScan)
  {
    this.assembliesToScan = assembliesToScan;
  }

  public AutoMapperModule(params Assembly[] assembliesToScan) : this((IEnumerable<Assembly>)assembliesToScan) { }

  protected override void Load(ContainerBuilder builder)
  {
    base.Load(builder);
    var assembliesToScan = this.assembliesToScan as Assembly[] ?? this.assembliesToScan.ToArray();

    var allTypes = assembliesToScan
                  .Where(a => !a.IsDynamic && a.GetName().Name != nameof(AutoMapper))
                  .Distinct() // avoid AutoMapper.DuplicateTypeMapConfigurationException
                  .SelectMany(a => a.DefinedTypes)
                  .ToArray();

    var openTypes = new[] {
                            typeof(IValueResolver<,,>),
                            typeof(IMemberValueResolver<,,,>),
                            typeof(ITypeConverter<,>),
                            typeof(IValueConverter<,>),
                            typeof(IMappingAction<,>)
            };

    foreach (var type in openTypes.SelectMany(openType =>
     allTypes.Where(t => t.IsClass && !t.IsAbstract && ImplementsGenericInterface(t.AsType(), openType))))
    {
      builder.RegisterType(type.AsType()).InstancePerDependency();
    }

    builder.Register<IConfigurationProvider>(ctx => new MapperConfiguration(cfg => cfg.AddMaps(assembliesToScan))).SingleInstance();

    builder.Register<IMapper>(ctx => new Mapper(ctx.Resolve<IConfigurationProvider>(), ctx.Resolve)).InstancePerDependency();
  }

  private static bool ImplementsGenericInterface(Type type, Type interfaceType)
            => IsGenericType(type, interfaceType) || type.GetTypeInfo().ImplementedInterfaces.Any(@interface => IsGenericType(@interface, interfaceType));

  private static bool IsGenericType(Type type, Type genericType)
            => type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == genericType;
}

  在Program中注册:

builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{

  containerBuilder.RegisterModule(new AutoMapperModule(Assembly.GetAssembly(typeof(MappingProfile))));
});

  

1. NuGet引用 
AutoMapper

AutoMapper.Extensions.Microsoft.DependencyInjection

标签:type,System,AotoFac,typeof,注册,AutoMapper,using,assembliesToScan
From: https://www.cnblogs.com/friend/p/16915214.html

相关文章