如何在Unity中注册AutoMapper配置文件 [英] How to register an AutoMapper profile with Unity

查看:336
本文介绍了如何在Unity中注册AutoMapper配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下AutoMapper配置文件:

I have the following AutoMapper profile:

public class AutoMapperBootstrap : Profile
{
    protected override void Configure()
    {
        CreateMap<Data.EntityFramework.RssFeed, IRssFeed>().ForMember(x => x.NewsArticles, opt => opt.MapFrom(y => y.RssFeedContent));
        CreateMap<IRssFeedContent, Data.EntityFramework.RssFeedContent>().ForMember(x => x.Id, opt => opt.Ignore());
    }
}

我正在像这样初始化它:

And I am initializing it like this:

var config = new MapperConfiguration(cfg =>
{
       cfg.AddProfile(new AutoMapperBootstrap());
});

container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());

当我尝试将其注入到我的构造函数中时:

When I try to inject it in my constructor:

private IMapper _mapper;
public RssLocalRepository(IMapper mapper)
{
    _mapper = mapper;
}

我收到以下错误:

当前类型AutoMapper.IMapper是一个接口,不能为 建造.您是否缺少类型映射?

The current type, AutoMapper.IMapper, is an interface and cannot be constructed. Are you missing a type mapping?

如何使用Unity正确初始化AutoMapper配置文件,以便可以通过DI在任何地方使用映射器?

How can I initialize the AutoMapper profile properly with Unity, so that I can use the mapper anywhere through DI?

推荐答案

在您的示例中,您将创建命名映射:

In your example you are creating named mapping:

// named mapping with "Mapper name"
container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());

但是您的解析器将如何知道该名称?

But how your resolver will know about this name?

您需要注册不带名称的映射:

You need to register you mapping without name:

// named mapping with "Mapper name"
container.RegisterInstance<IMapper>(config.CreateMapper());

它将映射器实例映射到IMapper接口,并且该实例将在解析接口上返回

It will map your mapper instance to IMapper interface and this instance will be returned on resolving interface

这篇关于如何在Unity中注册AutoMapper配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆