2010-09-01 159 views
10

我在使用Ninject将AutoMapper注入ASP.NET MVC 2应用程序时遇到问题。我用吉米博加德的文章AutoMapper and StructureMap type Configuration作为指导。使用Ninject注入AutoMapper依赖关系

public class AutoMapperModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<ITypeMapFactory>().To<TypeMapFactory>(); 
     Bind<Configuration>().ToSelf().InSingletonScope().WithConstructorArgument("mapper", MapperRegistry.AllMappers); 
     Bind<IConfiguration>().To<Configuration>(); 
     Bind<IConfigurationProvider>().To<Configuration>(); 
     Bind<IMappingEngine>().To<MappingEngine>(); 
    } 
} 

Ninject在解析Configuration时抛出异常。

激活IObjectMapper错误 没有匹配的绑定可用,且类型不可自行绑定。 激活路径:
3)依赖IObjectMapper的注入型配置的构造函数的参数映射器

更新

现在,这是使用以下绑定工作:

Bind<ITypeMapFactory>().To<TypeMapFactory>(); 
    Bind<Configuration>().ToConstant(new Configuration(Kernel.Get<ITypeMapFactory>(), MapperRegistry.AllMappers())).InSingletonScope(); 
    Bind<IConfiguration>().ToMethod(c => c.Kernel.Get<Configuration>()); 
    Bind<IConfigurationProvider>().ToMethod(c => c.Kernel.Get<Configuration>()); 
    Bind<IMappingEngine>().To<MappingEngine>(); 

我在GitHub上发布模块。 AutoMapper.Ninject。我的博客上的更多信息:http://binaryspeakeasy.com/2010/09/automapper-ninject/

+0

请参阅http://stackoverflow.com/a/1810728/11635 – 2012-06-12 06:21:30

回答

1

我得到它的工作,但它不觉得很干净创建一个配置类的实例。任何建议进一步清理它。

 Bind<ITypeMapFactory>().To<TypeMapFactory>(); 
     Bind<Configuration>().ToConstant(new Configuration(Kernel.Get<ITypeMapFactory>(), MapperRegistry.AllMappers())).InSingletonScope(); 
     Bind<IConfiguration>().ToMethod(c => c.Kernel.Get<Configuration>()); 
     Bind<IConfigurationProvider>().ToMethod(c => c.Kernel.Get<Configuration>()); 
     Bind<IMappingEngine>().To<MappingEngine>(); 
+1

最好将其编辑为您的问题。一般来说,我会说你过度使用Bind ().ToMethod(c => c.Kernel.Get ()'。只需使用'Bind ()。到()' – 2010-09-02 08:01:18

+1

同上'绑定<配置>()。ToConstant(新配置(Kernel.Get (),MapperRegistry.AllMappers()))。InSingletonScope();'应该映射到'.To <>。WithConstructorArgument' .... – 2010-09-02 08:09:17

2

这也可能是一个好主意,介绍一个映射门面。代替将IMappingEngine传入您的代码中创建一个IObjectMapper接口。我使用的接口包含直接从自动加载程序代码中取出的方法签名。

public interface IObjectMapper 
{ 
    TDestination Map(TSource source); 
    TDestination Map(TSource source, TDestination destination); 
    object Map(object source, Type sourceType, Type destinationType); 
    object Map(object source, object destination, Type sourceType, Type destinationType); 
} 

您的配置仍然依赖于自动映射器。

一篇博客文章中我就可以写的是在这里:http://fodonnel.wordpress.com/2010/09/20/an-object-mapper-facade/

+0

博客链接已经死了。 – mlhDev 2016-10-19 15:11:21

11

你可以做到这一点是使用最新版本(目前2.2.0)一一行。

作为一个额外的,我也有fodonnel同意,增加了门面隐藏Automapper接口是一个好主意,但是我不会从Automapper直接拿签名,除非你需要所有的功能。