You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ninject如何注册IValidation所有实现类并注入IEnumerable<IValidation>?

Fixing Ninject's IEnumerable Injection Issue

Hey there! I’ve run into this exact scenario before with Ninject, so let’s walk through how to get those validation implementations showing up in your Handler constructor.

First, Let’s Diagnose the Common Culprits

  • Double-check your assembly scanning target
    The FromAssemblyContaining<IValidation>() call only scans the assembly where IValidation is defined. If your NationalIdValidation or PassportValidation live in a different assembly, they won’t be picked up. Fix this by either:

    • Adding additional FromAssemblyContaining<NationalIdValidation>() calls for each assembly with implementations, or
    • Using FromAssembliesMatching("YourAssemblyPrefix*.dll") to scan multiple related assemblies.
  • Ensure your validation classes are valid candidates
    Ninject won’t pick up abstract classes or classes that don’t directly inherit/implement IValidation. Double-check:

    • No abstract modifier on your validation classes
    • Explicit : IValidation on each class (no typos in the interface name!)

Adjust Your Binding Syntax

Your current BindAllInterfaces might be overcomplicating things. Try a more explicit binding that directly targets IValidation:

Kernel.Bind(scan => scan
    .FromAssemblyContaining<IValidation>()
    // Add other assemblies here if needed: .FromAssemblyContaining<NationalIdValidation>()
    .SelectAllClasses()
    .InheritedFrom<IValidation>()
    .BindToSelf()
    .Bind<IValidation>());

Or if you prefer a more concise approach:

using System.Reflection;

Kernel.Bind<IValidation>()
      .ToAllTypesOf<IValidation>()
      .InAssembly(Assembly.GetAssembly(typeof(IValidation)));

Verify the Binding Works Manually

To confirm the issue isn’t with your Handler class, test retrieving the instances directly after registration:

var allValidations = Kernel.GetAll<IValidation>();
// Check if allValidations has the count you expect

If this returns an empty collection, the problem is definitely in your scanning/binding setup, not the Handler constructor.

Check for Scope Conflicts (Less Likely, But Worth Ruling Out)

If you’ve set custom scopes (like InSingletonScope()) for either the validations or the Handler, make sure their scopes are compatible. By default, Ninject uses transient scope, so this shouldn’t be an issue unless you’ve modified it.


内容的提问来源于stack exchange,提问作者zmaten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:31:13