在aspnetboilerplate asp.net核心项目上工作,在自定义映射方面遇到困难。想要创建自定义地图,并希望像AUTOMAP profiler一样使用它多次。遵循documentation,但未能在我的项目中实现。 我的步骤是
1)在XXX.Core下创建一个类MyModule
[DependsOn(typeof(AbpAutoMapperModule))]
public class MyModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Modules.AbpAutoMapper().Configurators.Add(config =>
{
config.CreateMap<CreateUserInput, CreatUserOutput>()
.ForMember(u => u.Password, options => options.Ignore())
.ForMember(u => u.OutputEmailAddress, options => options.MapFrom(input => input.EmailAddress));
});
}
}
public class CreateUserInput
{
public string Name { get; set; }
public string Surname { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
}
public class CreatUserOutput
{
public string OutputName { get; set; }
public string Surname { get; set; }
public string OutputEmailAddress { get; set; }
public string Password { get; set; }
}
2)在xxx上使用了以上配置。应用程序,服务如下所示
try
{
CreateUserInput te = new CreateUserInput
{
EmailAddress = "a@yahoo.com",
Name = "input",
Password = "test",
Surname = "sure"
};
CreatUserOutput ot = new CreatUserOutput();
var temp = _objectMapper.Map<CreatUserOutput>(te);
}
catch (System.Exception ex)
{
}
我不明白如何将自定义映射器与在服务上注入的IObjectMapper一起使用。
答案 0 :(得分:0)
更好地创建单独的自动映射器配置文件。 您需要在 Application 层中完全创建文件 您可以将其命名为AutoMapperProfile.cs 具有以下内容:
public class AutoMapperProfile : AutoMapper.Profile {
public AutoMapperProfile () {
CreateMap<CreateUserInput, CreatUserOutput> ()
.ForMember (u => u.Password, options => options.Ignore ())
.ForMember (u => u.OutputEmailAddress, options => options.MapFrom (input => input.EmailAddress));
}
}
要使此代码有效,请确保您使用ApplicationModule.cs 包含以下负责加载配置文件的代码。
public override void Initialize () {
var thisAssembly = typeof (LicenseManagerApplicationModule).GetAssembly ();
IocManager.RegisterAssemblyByConvention (thisAssembly);
Configuration.Modules.AbpAutoMapper ().Configurators.Add (
// Scan the assembly for classes which inherit from AutoMapper.Profile
cfg => cfg.AddProfiles (thisAssembly)
);
}