使用NInject

时间:2016-06-17 12:29:53

标签: c# ninject automapper

我想使用NInject将AutoMapper.IMapper单个实例注入singleton

实际上,我使用AutoMapper静态API取消/映射对象。它已经过时了,我期待利用ocassion来使用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>();

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我对此进行了调查。

我发现了以下内容:

在文档中我们可以发现我们可以做类似的事情:

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,因为您对configurationmapper具有约束力。

但在这里我们有两个问题。 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的公共/内部构造函数具有相同的情况。

这应该有所帮助。