问题 AutoMapper 4.2和Ninject 3.2


我正在更新我的一个项目以使用AutoMapper 4.2,我正在遇到破坏性的变化。当我 似乎 为了解决上述变化,我并不完全相信我是以最合适的方式做到的。

在旧代码中,我有一个 NinjectConfiguration, 和 AutoMapperConfiguration 每个由WebActivator加载的类。在新版本中 AutoMapperConfiguration 退出,我改为实例 MapperConfiguration 直接在 NinjectConfiguration 绑定发生的类,如下所示:

private static void RegisterServices(
    IKernel kernel) {
    var profiles = AssemblyHelper.GetTypesInheriting<Profile>(Assembly.Load("???.Mappings")).Select(Activator.CreateInstance).Cast<Profile>();
    var config = new MapperConfiguration(
        c => {
            foreach (var profile in profiles) {
                c.AddProfile(profile);
            }
        });

    kernel.Bind<MapperConfiguration>().ToMethod(
        c =>
            config).InSingletonScope();

    kernel.Bind<IMapper>().ToMethod(
        c =>
            config.CreateMapper()).InRequestScope();

    RegisterModules(kernel);
}

那么,这是使用Ninject绑定AutoMapper 4.2的适当方法吗?它似乎工作到目前为止,但我只是想确定。


2243
2018-02-05 21:38


起源



答案:


之前IMapper接口在库中不存在,因此您必须在下面实现接口和类并将它们绑定为单例模式。

public interface IMapper
{
    T Map<T>(object objectToMap);
}

public class AutoMapperAdapter : IMapper
{
    public T Map<T>(object objectToMap)
    {
        //Mapper.Map is a static method of the library!
        return Mapper.Map<T>(objectToMap);
    }
}

现在您只需将库的IMapper接口绑定到mapperConfiguration.CreateMapper()的单个实例

你的代码问题,你应该使用单个实例(或Ninject说,一个常量)绑定。

// A reminder
var config = new MapperConfiguration(
    c => {
        foreach (var profile in profiles) {
            c.AddProfile(profile);
        }
    });
// Solution starts here
var mapper = config.CreateMapper();
kernel.Bind<IMapper>().ToConstant(mapper);

14
2018-02-05 22:51



所以而不是 InRequestScope() 这应该 InSingletonScope()?否则绑定没问题? - Gup3rSuR4c
@Alex抱歉忘了代码示例,添加它。 - Sand King
太好了,这解决了我的问题。 - Dennis R


答案:


之前IMapper接口在库中不存在,因此您必须在下面实现接口和类并将它们绑定为单例模式。

public interface IMapper
{
    T Map<T>(object objectToMap);
}

public class AutoMapperAdapter : IMapper
{
    public T Map<T>(object objectToMap)
    {
        //Mapper.Map is a static method of the library!
        return Mapper.Map<T>(objectToMap);
    }
}

现在您只需将库的IMapper接口绑定到mapperConfiguration.CreateMapper()的单个实例

你的代码问题,你应该使用单个实例(或Ninject说,一个常量)绑定。

// A reminder
var config = new MapperConfiguration(
    c => {
        foreach (var profile in profiles) {
            c.AddProfile(profile);
        }
    });
// Solution starts here
var mapper = config.CreateMapper();
kernel.Bind<IMapper>().ToConstant(mapper);

14
2018-02-05 22:51



所以而不是 InRequestScope() 这应该 InSingletonScope()?否则绑定没问题? - Gup3rSuR4c
@Alex抱歉忘了代码示例,添加它。 - Sand King
太好了,这解决了我的问题。 - Dennis R