使用AutoMapper.Profile创建实例(非静态)映射器

时间:2015-03-16 15:16:54

标签: c# castle-windsor automapper ioc-container

我使用以下答案中描述的以下方法来创建映射器的实例:

var platformSpecificRegistry = AutoMapper.Internal.PlatformAdapter.Resolve<IPlatformSpecificMapperRegistry>();
platformSpecificRegistry.Initialize();

var autoMapperCfg = new AutoMapper.ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers);
var mappingEngine = new AutoMapper.MappingEngine(_autoMapperCfg);

如以下问题所述:

AutoMapper How To Map Object A To Object B Differently Depending On Context

我如何能够使用[重用] Automapper profile类来创建映射器的实例?

public class ApiTestClassToTestClassMappingProfile : Profile
{
    protected override void Configure()
    {
        base.Configure();
        Mapper.CreateMap<ApiTestClass, TestClass>()
            .IgnoreAllNonExisting();
    }
}

只是为了让您知道我为什么需要这样的功能: 我使用以下方法将所有Automapper Profile类注册到我的IoC容器[CastleWindsor]中:

    IoC.WindsorContainer.Register(Types.FromThisAssembly()
                                       .BasedOn<Profile>()
                                       .WithServiceBase()
                                       .Configure(c => c.LifeStyle.Is(LifestyleType.Singleton)));

    var profiles = IoC.WindsorContainer.ResolveAll<Profile>();

    foreach (var profile in profiles)
    {
        Mapper.AddProfile(profile);
    }

    IoC.WindsorContainer.Register(Component.For<IMappingEngine>().Instance(Mapper.Engine));

虽然上面完全满足了初始化我的静态Mapper类的需要,但我真的不知道如何重新使用我的Automapper配置文件类来创建实例映射器[使用非静态映射器]。

3 个答案:

答案 0 :(得分:5)

您需要确保您的Profile调用正确的CreateMap调用:

public class ApiTestClassToTestClassMappingProfile : Profile
{ 
    protected override void Configure()
    {
        CreateMap<ApiTestClass, TestClass>()
            .IgnoreAllNonExisting();
    }
}

基础Profile类上的CreateMap将该地图与该配置文件和配置相关联。

此外,您的IgnoreAllNonExisting应该被CreateMap调用中的MemberList.Source选项取代。这说&#34;使用源类型作为我的成员列表来验证而不是目的地类型&#34;。

答案 1 :(得分:1)

这是使用配置文件

创建MapperConfiguration的方法
public static class MappingProfile
{
    public static MapperConfiguration InitializeAutoMapper()
    {
        MapperConfiguration config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new WebMappingProfile());  //mapping between Web and Business layer objects
            cfg.AddProfile(new BLProfile());  // mapping between Business and DB layer objects
        });

        return config;
    }
}

个人资料示例

//Profile number one saved in Web layer
public class WebMappingProfile : Profile
{
    public WebMappingProfile()
    {
        CreateMap<Question, QuestionModel>();
        CreateMap<QuestionModel, Question>();
        /*etc...*/
    }
}

//Profile number two save in Business layer
public class BLProfile: Profile
{
    public BLProfile()
    {
        CreateMap<BLModels.SubModels.Address, DataAccess.Models.EF.Address>();
        /*etc....*/
    }
}

将automapper连接到DI框架(这是Unity)

public static class UnityWebActivator
{
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start()
    {
        var container = UnityConfig.GetConfiguredContainer();
        var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();
        container.RegisterInstance<IMapper>(mapper);

        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        // TODO: Uncomment if you want to use PerRequestLifetimeManager
        // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }

    /// <summary>Disposes the Unity container when the application is shut down.</summary>
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}

在您的班级中使用IMapper进行映射

public class BaseService
{
    protected IMapper _mapper;

    public BaseService(IMapper mapper)
    {
        _mapper = mapper;
    }

    public void AutoMapperDemo(){
        var questions = GetQuestions(token);
        return _mapper.Map<IEnumerable<Question>, IEnumerable<QuestionModel>>(questions);
    }

    public IEnumerable<Question> GetQuestions(token){
        /*logic to get Questions*/
    }
}

我的原始帖子可在此处找到:http://www.codeproject.com/Articles/1129953/ASP-MVC-with-Automapper-Profiles

答案 2 :(得分:0)

我最终创建了一个mapper实例工厂,如下所示:

using AutoMapper;
using AutoMapper.Mappers;
using System.Collections.Generic;

public class MapperFactory<TSource,TDestination> where TSource : new() where TDestination : new()
{
    private readonly ConfigurationStore _config;

    public MapperFactory(IEnumerable<Profile> profiles)
    {
        var platformSpecificRegistry = AutoMapper.Internal.PlatformAdapter.Resolve<IPlatformSpecificMapperRegistry>();

        platformSpecificRegistry.Initialize();

        _config = new AutoMapper.ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers);

        foreach (var profile in profiles)
        {
            _config.AddProfile(profile);
        }
    }

    public TDestination Map(TSource sourceItem)
    {
        using (var mappingEngine = new MappingEngine(_config))
        {
            return mappingEngine.Map<TSource, TDestination>(sourceItem);
        }             
    }
}

现在我可以在我的解决方案中使用类似以下的代码:

        var profiles = new Profile[]
        {
            new ApiTestClassToTestClassMappingProfile1(),
            new ApiTestClassToTestClassMappingProfile2(),
            new ApiTestClassToTestClassMappingProfile3() 
        };

        var mapper = new MapperFactory<ApiTestClass, TestClass>(profiles);

        var mappedItem = mapper.Map(testClassInstance);

以上代码可以最大限度地重用配置文件类。