Ninject如何注册IValidation所有实现类并注入IEnumerable<IValidation>?
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
TheFromAssemblyContaining<IValidation>()call only scans the assembly whereIValidationis defined. If yourNationalIdValidationorPassportValidationlive 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.
- Adding additional
Ensure your validation classes are valid candidates
Ninject won’t pick up abstract classes or classes that don’t directly inherit/implementIValidation. Double-check:- No
abstractmodifier on your validation classes - Explicit
: IValidationon each class (no typos in the interface name!)
- No
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

