簡體   English   中英

c# - 在類庫中使用 Automapper 進行 Ninject

[英]c# - Ninject with Automapper in class library

我將我的項目組織成類庫和一個主調用者(現在是一個控制台應用程序,然后是 Apis)。

  • DAL 庫
  • BL庫
  • 模型(實體)庫
  • Main(控制台應用程序)

我添加了 Automapper 並將其配置為在 DAL 和 BL 之間工作(模型將所有公開 BL 層的實體表示為與其他項目的共同點)。 這很好,但我決定通過 IoC 容器注入 IMapper,以便我可以將接口傳遞給構造函數。 記住我的架構,我如何為此目的配置 Ninject?

我將 Automapper 與“Api Instance”一起使用,如下所示:

var config = new MapperConfiguration(cfg => {
    cfg.AddProfile<AppProfile>();
    cfg.CreateMap<Source, Dest>();
});


var mapper = config.CreateMapper();

謝謝

解決方案:

在業務邏輯層我添加了一個 Ninject 模塊:

    public class AutomapperModule : NinjectModule
    {
        public StandardKernel Nut { get; set; }

        public override void Load()
        {
            Nut = new StandardKernel(); 
            var mapperConfiguration = new MapperConfiguration(cfg => { CreateConfiguration(); });
            Nut.Bind<IMapper>().ToConstructor(c => new AutoMapper.Mapper(mapperConfiguration)).InSingletonScope(); 
        }


        public IMapper GetMapper()
        {
            return Nut.Get<IMapper>();
        }

        private MapperConfiguration CreateConfiguration()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfiles(Assembly.GetExecutingAssembly());
                cfg.AddProfiles(Assembly.Load("DataAccess"));
            });

            return config;
        }
    }

它是 AutoMapper 網站上的示例和 Jan Muncinsky 的答案的混合體。

我還添加了一個 Get 方法來返回上下文映射器,只是為了幫助。 客戶端只需要調用這樣的東西:

var ioc = new AutomapperModule();
ioc.Load();
var mapper = ioc.GetMapper();

然后將映射器傳遞給構造函數......

如果您有更好的解決方案,請隨時發布。

以最簡單的形式,它很容易:

var kernel = new StandardKernel();
var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile<AppProfile>(); });
kernel.Bind<IMapper>().ToConstructor(c => new Mapper(mapperConfiguration)).InSingletonScope();

var mapper = kernel.Get<IMapper>();

使用 Ninject 模塊:

public class AutoMapperModule : NinjectModule
{
    public override void Load()
    {
        var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile<AppProfile>(); });
        this.Bind<IMapper>().ToConstructor(c => new Mapper(mapperConfiguration)).InSingletonScope();
        this.Bind<Root>().ToSelf().InSingletonScope();
    }
}

public class Root
{
    public Root(IMapper mapper)
    {
    }
}

...

var kernel = new StandardKernel(new AutoMapperModule());
var root = kernel.Get<Root>();

暫無
暫無

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

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