AutoMapper 4.2和Ninject 3.2

Gup*_*R4c 11 c# asp.net-mvc ninject automapper

我正在更新我的一个项目以使用AutoMapper 4.2,而我正在遇到破坏性的变化.虽然我似乎已经解决了这些变化,但我并不完全相信我已经以最合适的方式做到了这一点.

在旧代码中,我有一个NinjectConfiguration和一个AutoMapperConfiguration类,每个都由WebActivator加载.在新版本中,AutoMapperConfigurationdrop out和我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);
}
Run Code Online (Sandbox Code Playgroud)

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

San*_*ing 14

之前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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您只需将库的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);
Run Code Online (Sandbox Code Playgroud)