[英]AutoMapper not instantiating IMappingEngine using SimpleInjector and WebApi2
我開始在項目(WebApi2,框架4.5.1)中使用AutoMapper(來自Nuget的最新版本),並使用SimpleInjector(來自Nuget的最新版本)。
我的問題是我不知道如何配置SimpleInjector以便通過構造函數將IMappingEngine注入到我的模型中。
現在,我遇到了錯誤:未 映射的屬性:MappingEngine
我正在使用IMappingEngine界面。
我有一個帶有所有Mapper.CreateMap <>的AutoMapperProfile類
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();
}
然后,每個Controller在構造函數中接收一個IMappingEngine並使用:
MappingEngine.Map<>
模型類樣本
public class EntityModel : BaseModel.BaseModel<EntityModel >
{
public EntityModel(IMappingEngine mappingEngine) : base(mappingEngine)
{
}
}
基本模型
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沒有注入到模型的構造函數中。 問題是如何使其工作。
當我嘗試執行.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)
有什么缺失或錯誤嗎?
提前致謝! 吉列爾莫。
由於您的EntityController
已由Simple Injector正確解析,並且取決於IMapperEngine
,因此可以放心確保正確注入了映射器引擎。 可能發生的情況是當時注冊的Mapper.Engine
沒有正確初始化,但我只是在猜測。 Automapper專家應該能夠看到這里出了什么問題。
但是,問題的核心是您嘗試將依賴項注入到域實體中。 看一下Jimm Bogard (Automapper的創建者)的這篇文章,他解釋了為什么這是一個壞主意。
一旦您在實體初始化期間停止要求服務依賴性,此問題將完全消失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.