AutoMapper不使用SimpleInjector和WebApi2实例化IMappingEngine

时间:2015-11-18 19:32:20

标签: c# asp.net-web-api asp.net-web-api2 automapper simple-injector

我开始使用AutoMapper(Nuget的最新版本)到我的项目(WebApi2,框架4.5.1)和使用SimpleInjector(Nuget的最新版本)。

我的问题是我不知道如何配置SimpleInjector以通过构造函数将IMappingEngine注入到我的模型中。

现在我收到错误:     未映射的属性:MappingEngine

我正在使用IMappingEngine界面。

我有一个AutoMapperProfile类,包含所有Mapper.CreateMap<>

AutoMapperConfig的示例

public class WebApiAutomapperProfile : Profile
{
    /// <summary>
    /// The configure.
    /// </summary>
    protected override void Configure()
    {
        this.CreateMap<Entity, EntityModel>();
    }
}

模型接收IMappingEngine的原因是某些映射属性内部有其他映射。

Global.asax (方法Application_Start())我正在致电:

 GlobalConfiguration.Configure(WebApiConfig.Register);

 webApiContainer = new Container();

 webApiContainer.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

 IocConfig.RegisterIoc(GlobalConfiguration.Configuration, webApiContainer);

IocConfig.cs

public static class IocConfig
{
    public static void RegisterIoc(HttpConfiguration config, Container container)
    {
        InstallDependencies(container);
        RegisterDependencyResolver(container);
    }

    private static void InstallDependencies(Container container)
    {
        new ServiceInstallerSimpleInjector().Install(container);
    }

    private static void RegisterDependencyResolver(Container container)
    {
        GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
    }

ServiceInstallerSimpleInjector

public class ServiceInstallerSimpleInjector : IServiceInstallerSimpleInjector
{
    // Automapper registrations
    container.Register(typeof(ITypeMapFactory), typeof(TypeMapFactory), Lifestyle.Scoped);
    container.RegisterCollection<IObjectMapper>(MapperRegistry.Mappers);

    var configurationRegistration = Lifestyle.Scoped.CreateRegistration<ConfigurationStore>(container);
    container.AddRegistration(typeof(IConfiguration), configurationRegistration);
    container.AddRegistration(typeof(IConfigurationProvider), configurationRegistration);

    // The initialization runs all the map creation once so it is then done when you come to do your mapping. 
    // You can create a map whenever you want, but this will slow your code down as the mapping creation involves reflection.

    Mapper.Initialize(config =>
    {
        config.ConstructServicesUsing(container.GetInstance);
        config.AddProfile(new WebApiAutomapperProfile());
        config.AddGlobalIgnore("Errors");
        config.AddGlobalIgnore("IsModelValid");
        config.AddGlobalIgnore("BaseValidator");
        config.AddGlobalIgnore("AuditInformation");
     });

     container.RegisterSingleton<IMappingEngine>(Mapper.Engine);

     Mapper.AssertConfigurationIsValid();

     container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

     container.Verify();
}

然后每个控制器在构造函数中接收IMappingEngine并使用:

MappingEngine.Map<>

模型类示例

public class EntityModel : BaseModel.BaseModel<EntityModel >
{
    public EntityModel(IMappingEngine mappingEngine) : base(mappingEngine)
    {
    }
}

BaseModel

public abstract class BaseModel<T> : IBaseModel
        where T : class
{
    public IMappingEngine MappingEngine { get; set; }

    protected BaseModel(IMappingEngine mappingEngine)
    {
        this.MappingEngine = mappingEngine;
    }
}

错误消息显示:

Type needs to have a constructor with 0 args or only optional args\r\nParameter name: type

Mapping types:
Entity -> EntityModel
Model.Entity -> WebApi.Models.EntityModel

Destination path:
EntityModel

Source value:
System.Data.Entity.DynamicProxies.Entity_1D417730D5BE3DEAF6292D57AB49B32FA18136A1DCF74193E8716EC6EE4DC62B

问题是IMappingEngine mappingEngine没有被注入到Model的构造函数中。问题是如何使其发挥作用。

当我尝试执行.Map

时会抛出错误
return this.MappingEngine.Map<Entity,EntityModel>(this.EntityRepository.AllMaterialized().FirstOrDefault());

这是Stacktrace

   at WebApi.Controllers.Api.EntityController.Get() in c:\Users\Guillermo\Downloads\Backend\WebApi\Controllers\Api\EntityController.cs:line 108
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

有什么遗漏或错误吗?

提前致谢!吉列尔莫。

1 个答案:

答案 0 :(得分:1)

由于Simple Injector正确解析了EntityController,并且它依赖于IMapperEngine,因此您可以确保正确注入映射器引擎。可能发生的是注册的Mapper.Engine在那时没有正确初始化,但我只是猜测这个。 Automapper专家应该能够看到这里出了什么问题。

然而,问题的核心是您尝试将依赖注入到域实体中。看看this article from Jimmy Bogard(Automapper的创建者)谁解释了为什么这是一个坏主意。

在实体初始化期间停止要求服务依赖性后,此问题将完全消失。