【问题标题】:What options do I have for automating bindings with NInject我有哪些选项可以使用 NInject 自动绑定
【发布时间】:2011-01-12 01:18:37
【问题描述】:

建议使用哪些方法和模式(如果有)来自动设置绑定,而不是手动绑定每个类?

例如,绝大多数绑定看起来像这样:

Bind<ICustomerRepository>.To<CustomerRepository>();

一旦模块变大,您最终可能会得到 100 多个看起来完全相同的绑定。这可以自动化吗?

【问题讨论】:

    标签: ninject


    【解决方案1】:

    查看约定扩展: https://github.com/ninject/ninject.extensions.conventions

            using (IKernel kernel = new StandardKernel())
            {
                var scanner = new AssemblyScanner();
                scanner.From(Assembly.GetExecutingAssembly());
                scanner.BindWith<DefaultBindingGenerator>();
                kernel.Scan(scanner);
                var instance = kernel.Get<IDefaultConvention>();
    
                instance.ShouldNotBeNull();
                instance.ShouldBeInstanceOf<DefaultConvention>();
            }
    

    【讨论】:

    • 你能解释一下这是做什么的吗?
    • 这个项目中有几个不同的 BindingGenerators 将扫描您的程序集并根据约定在 Ninject 中创建绑定。此示例中使用的 DefaultBindingGenerator 查找与具体实例同名的接口加上“I”。例如,在上面的 IDefaultConvention 绑定到 DefaultConvention。如果你想为绑定指定规则,还有一个 RegexBindingGenerator,还有一个 GenericBindingGenerator 用于尝试自动满足类型的泛型参数。
    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 2013-10-06
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多