使用Unity注册AutoMapper失败

时间:2017-01-06 16:16:50

标签: automapper unity-container

我有以下代码来注册Mapping(版本4.2)

public class ModelMapperProfile : Profile
{

    protected override void Configure()
    {
        CreateMap<Case, CaseModel>();
        CreateMap<CaseDetail, CaseDetailModel>();
    }
}
public static class AutoMapperService
{
    public static MapperConfiguration Initialize()
    {
        MapperConfiguration config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<ModelMapperProfile>();
        });

        return config;
    }
}

我使用unity注册依赖关系如下......

public static void RegisterTypes(IUnityContainer container)
{

    container.LoadConfiguration();
    var mapper = AutoMapperService.Initialize()
                                .CreateMapper();
    container.RegisterInstance<IMapper>(mapper);
}

我的服务构造函数..

public TaxLiabilityCaseService(IMapper mapper,
        IUnitOfWork unitofWork,
        IRepository<Case> caseR,
        IRepository<CaseDetail> caseDetailR)
    {
        _mapper = mapper;
        _unitofWork = unitofWork;
        _caseR = caseR;
        _caseDetailR = caseDetailR;
    }

我收到以下错误消息..

当前类型AutoMapper.IMapper是一个接口,无法构造。你错过了类型映射吗?

Answers found here did not work for me

我在这里缺少什么

1 个答案:

答案 0 :(得分:1)

尝试按照以下步骤操作(MVC5):

获取Unity Nuget包:

Unity.Mvc5

创建此类:

public class MapperConfig
    {
        public static IMapper Mapper { get; set; }
        public static void RegisterProfiles()
        {
            var config = new MapperConfiguration(cfg =>
            {
               // add profiles here
            });
            config.AssertConfigurationIsValid();
            Mapper = config.CreateMapper();
        }
    }

UnityConfig文件(由包创建)中,添加:

public static void RegisterComponents()
     {
          var container = new UnityContainer();
          container.RegisterInstance<IMapper>(MapperConfig.Mapper);
     }

Global.asax中添加以下内容:

protected void Application_Start()
        {
            MapperConfig.RegisterProfiles();
            UnityConfig.RegisterComponents(); 
        }

此后你应该好。