代码之家  ›  专栏  ›  技术社区  ›  Max Bertoli

c#-类库中带有Automapper的Ninject

  •  1
  • Max Bertoli  · 技术社区  · 7 年前

    我将项目组织到类库和主调用者中(现在是控制台应用程序,然后是API)。

    • DAL库
    • BL库
    • 模型(实体)库
    • 主(控制台应用程序)

    我添加了Automapper,并将其配置为在DAL和BL之间工作(模型将所有暴露BL层的实体表示为与其他项目相同的点)。 这很好,但我决定通过IoC容器注入IMapper,以便将接口传递给构造函数。 记住我的体系结构,我如何配置Ninject来实现这一目的?

    我将Automapper与“Api实例”一起使用,如下所示:

    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方法,用于返回上下文映射器,仅用于helper。 客户只需调用以下内容:

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

    然后将映射器传递给构造函数。。。

    如果您有更好的解决方案,请随时发布。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jan Muncinsky    7 年前

    最简单的形式是:

    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>();