将Ninject ToConstant转换为Simple Injector实现及等价代码问询
Converting Ninject's
ToConstant to Simple Injector Let's walk through converting your Ninject code to its Simple Injector equivalent, including handling the validator factory and constant registration.
First, here's your original Ninject code for reference:
Func<Type, IValidator> validatorFactory = type => { var valType = typeof(Validator<>).MakeGenericType(type); return (IValidator)kernel.Get(valType); }; kernel.Bind<IValidationProvider>().ToConstant(new ValidationProvider(validatorFactory));
Simple Injector Equivalent Code
// 1. First register the open generic validator mapping (Simple Injector requires explicit open generic registration) container.Register(typeof(IValidator<>), typeof(Validator<>)); // 2. Create the validator factory using Simple Injector's container instance Func<Type, IValidator> validatorFactory = type => { var validatorType = typeof(IValidator<>).MakeGenericType(type); return (IValidator)container.GetInstance(validatorType); }; // 3. Register the pre-created ValidationProvider instance (equivalent to Ninject's ToConstant) container.RegisterInstance<IValidationProvider>(new ValidationProvider(validatorFactory));
Key Notes:
- Open Generic Registration: Unlike Ninject, Simple Injector requires explicit registration of open generic types (like
IValidator<>) instead of resolving them automatically. This line ensures any closed genericIValidator<T>will map toValidator<T>. ToConstant→RegisterInstance: Ninject'sToConstantregisters a pre-instantiated object as a singleton. In Simple Injector,RegisterInstancedoes exactly this—by default, the instance is treated as a singleton (you can adjust the lifecycle with an overload if needed, but this matches Ninject's default behavior forToConstant).- Factory Logic: The core factory logic remains nearly identical; we just replace
kernel.Getwithcontainer.GetInstanceto resolve the generic validator type from Simple Injector's container.
Optional: More Idiomatic Simple Injector Approach
If your ValidationProvider accepts a Func<Type, IValidator> as a constructor parameter, you can let Simple Injector auto-generate this factory for you instead of creating it manually:
// Register open generic validators container.Register(typeof(IValidator<>), typeof(Validator<>)); // Simple Injector will automatically resolve the Func<Type, IValidator> for you container.Register<IValidationProvider, ValidationProvider>(Lifestyle.Singleton);
This is cleaner because Simple Injector can build the factory delegate automatically, removing the need to manually construct and register the ValidationProvider instance.
内容的提问来源于stack exchange,提问作者Mike Flynn
相关产品推荐
相关产品推荐

