簡體   English   中英

AutoMapper 4.2和Ninject 3.2

[英]AutoMapper 4.2 and Ninject 3.2

我正在更新我的一個項目以使用AutoMapper 4.2,而我正在遇到破壞性的變化。 雖然我似乎已經解決了這些變化,但我並不完全相信我已經以最合適的方式做到了這一點。

在舊代碼中,我有一個NinjectConfiguration和一個AutoMapperConfiguration類,每個類都由WebActivator加載。 在新版本中, AutoMapperConfiguration退出,我在NinjectConfiguration類中直接實例化MapperConfiguration ,其中綁定正在發生,如下所示:

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的適當方法嗎? 它似乎工作到目前為止,但我只是想確定。

之前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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM