使用NInject注入自动缩放器映射器
  我想使用NInject注入一个AutoMapper.IMapper单实例作为singleton 。 
实际上,我使用AutoMapper静态API将对象从/映射到/映射到对象。 它已经过时了,我期待着利用这个方法来使用NInject注入它。
  目前,我使用此代码来创建我的IMapper实例: 
AutoMapper.Mapper.AddProfile(new UI.Mappings.Profiles.DigitalResourceProfile());
AutoMapper.Mapper.AddProfile(new UI.Mappings.Profiles.DigitalInputProfile());
AutoMapper.Mapper.AddProfile(new UI.Mappings.Profiles.FollowUpActivityProfile());
AutoMapper.Mapper.AddProfile(new UI.Mappings.Profiles.ResourceProfile());
正如你所看到的,我也有一些配置文件要初始化。
我应该如何构建所有这些?
  到目前为止,我只能创建一个Module但我不知道如何创建绑定。 
public class AutoMapperModule : Ninject.Modules.NinjectModule
{
    public override void Load()
    {
        this.Bind<AutoMapper.MapperConfiguration>().ToProvider<AutoMapperconfigurationProvider>().InSingletonScope();
        this.Bind<AutoMapper.IMapper>().To<AutoMapper.Mapper>();
    }
    private class AutoMapperconfigurationProvider : IProvider<AutoMapper.MapperConfiguration>
    {
        public object Create(IContext context)
        {
            AutoMapper.MapperConfiguration instance = new AutoMapper.MapperConfiguration(
                cfg =>
                {
                    cfg.AddProfile(new UI.Mappings.Profiles.DigitalResourceProfile());
                    cfg.AddProfile(new UI.Mappings.Profiles.DigitalInputProfile());
                    cfg.AddProfile(new UI.Mappings.Profiles.FollowUpActivityProfile());
                    cfg.AddProfile(new UI.Mappings.Profiles.ResourceProfile());
                }
            );
            return instance;
        }
        public Type Type
        {
            get { throw new NotImplementedException(); }
        }
    }
}
  每次我需要一个IMapper来映射对象时,我想写这个句子: 
IMapper mapper = kernel.Get<IMapper>();
有任何想法吗?
我调查了这一点。
我发现以下内容:
在文档中,我们可以发现我们可以执行如下操作:
var config = new MapperConfiguration(cfg => {
    cfg.AddProfile<SomeProfile>();
    cfg.CreateMap<Source, Dest>();
});
var mapper = config.CreateMapper(); // option 1
// or
var mapper = new Mapper(config); // option 2
  你的代码可以使用option 2 ,因为你有configuration和mapper绑定。 
  但在这里我们有两个问题。  1)您需要更改第一个绑定,将MapperConfiguration绑定为接口IConfigurationProvider因为Mapper的构造函数需要它: 
public Mapper(IConfigurationProvider configurationProvider)
    : this(configurationProvider, configurationProvider.ServiceCtor)
{
}
但是,我们遇到了第二个问题。
  2)在automapper 4.2.1版本中 (因为我相信你是从NuGet下载的), Mapper类只有internal构造函数。  它在文档中有一个公共的构造函数(这很奇怪),我认为它将在未来的版本中使用。 
  因此,现在您需要修改Load方法以使用option 1 : 
public override void Load()
{
    this.Bind<AutoMapper.MapperConfiguration>().ToProvider<AutoMapperconfigurationProvider>().InSingletonScope();
    this.Bind<AutoMapper.IMapper>().ToMethod(context => context.Kernel.Get<MapperConfiguration>().CreateMapper());
}
  然后你可以调用IMapper mapper = kernel.Get<IMapper>();  获取映射器实例。 
  它将使用public IMapper CreateMapper() => new Mapper(this);  并将创建IMapper的实例。  注意:您需要使用MapperConfiguration(而不是IConfiguration提供者)来调用CreateMapper方法,它与Mapper公共/内部构造函数具有相同的情况。 
这应该有所帮助。
链接地址: http://www.djcxy.com/p/74401.html