繁体   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