我正在使用 Automapper 5.2。我已经用作基础this关联。我将分步骤描述设置 Automapper 的过程。
首先我按照指示将 Automapper 添加到 Project.json:
PM> Install-Package AutoMapper
其次我创建了一个名为“Mappings”的文件夹来保存所有与映射相关的文件
第三 我在mappings 文件夹中自己的文件中设置了Automapper 的配置:
public class AutoMapperConfiguration
{
public MapperConfiguration Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ViewModelToDomainMappingProfile>();
cfg.AddProfile<DomainToViewModelMappingProfile>();
cfg.AddProfile<BiDirectionalViewModelDomain>();
});
return config;
}
}
Forth 同样在 mappings 文件夹中它自己的文件中,我按如下方式设置了映射配置文件:
public class DomainToViewModelMappingProfile : Profile
{
public DomainToViewModelMappingProfile()
{
CreateMap<Client, ClientViewModel>()
.ForMember(vm => vm.Creator, map => map.MapFrom(s => s.Creator.Username))
.ForMember(vm => vm.Jobs, map => map.MapFrom(s => s.Jobs.Select(a => a.ClientId)));
}
}
第五,我在映射文件夹中添加了一个扩展方法作为它自己的文件...接下来在 startup.cs 中使用了它:
public static class CustomMvcServiceCollectionExtensions
{
public static void AddAutoMapper(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
var config = new AutoMapperConfiguration().Configure();
services.AddSingleton<IMapper>(sp => config.CreateMapper());
}
}
第六我在Startup.cs的ConfigureServices方法中添加了这一行
// Automapper Configuration
services.AddAutoMapper();
最后我在 Controller 中使用它来转换集合...
IEnumerable<ClientViewModel> _clientVM = Mapper.Map<IEnumerable<Client>, IEnumerable<ClientViewModel>>(_clients);
根据我之前提到的问题,我以为我已经设置好了一切,所以我可以使用它,但是我在 Controller 的上面一行中遇到了错误...
"Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance."
我错过了什么..这是设置 Automapper 的正确方法吗?我怀疑我在这里错过了一步。非常感谢任何帮助。
最佳答案
AutoMapper 有两种用法:依赖注入(inject)和用于向后兼容的较旧的静态。您正在为依赖注入(inject)配置它,但随后尝试使用静态。那是你的问题。您只需要选择一种方法,然后选择另一种方法。
如果你想用依赖注入(inject)来做,你的 Controller 应该把映射器作为构造函数参数保存到一个成员,然后你需要使用那个成员来做你的映射:
public class FooController : Controller
{
private readonly IMapper mapper;
public FooController(IMapper mapper)
{
this.mapper = mapper;
}
然后:
IEnumerable<ClientViewModel> _clientVM = mapper.Map<IEnumerable<Client>, IEnumerable<ClientViewModel>>(_clients);
对于静态方法,您需要使用您的配置初始化 AutoMapper:
public MapperConfiguration Configure()
{
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.AddProfile<ViewModelToDomainMappingProfile>();
cfg.AddProfile<DomainToViewModelMappingProfile>();
cfg.AddProfile<BiDirectionalViewModelDomain>();
});
}
然后你只需要在 Startup.cs 中调用这个方法;您将不再注册单例。
关于c# - Automapper 错误说映射器未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41284349/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到rubygems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc