c# - 如何使用 Unity 注册 AutoMapper 配置文件

标签 c# unity-container automapper

我有以下 AutoMapper 配置文件:

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());
    }
}

我正在这样初始化它:

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

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

当我尝试将它注入(inject)我的构造函数时:

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

我收到以下错误:

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

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

最佳答案

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

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

但是您的解析器如何知道这个名称呢?

你需要在没有名字的情况下注册你的映射:

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

它将您的映射器实例映射到IMapper 接口(interface),并且该实例将在解析接口(interface)时返回

关于c# - 如何使用 Unity 注册 AutoMapper 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36780573/

相关文章:

C# 将文件读入字符串数组并将其打印到文本框中

c# - 如何将暴露给 COM 互操作的 .NET 对象标记为单线程?

c# - 具有相同类型的命名和未命名注册的意外 Unity 容器行为

c# - Automapper ResolveUsing 原因 "Can' t 将此解析为可查询表达式”

nhibernate - 如何使用 AutoMapper 简单地将 NHibernate ISet 映射到 IList

c# - Entity Framework 可以使用单个 SaveChanges() 添加许多相关实体吗?

c# - Travis CI 上使用 Mono 的 NuGet 包恢复失败

c# - 为什么 IOC 容器被认为是一种减少耦合的方式?

c# - 我可以将构造函数参数传递给 Unity 的 Resolve() 方法吗?

c# - AutoMapper 从 3.3.1 更新到 4.0.4 映射失败