Can SimpleInjector register an initializer for generic types at runtime?

Can I register initializers for generic types with SimpleInjector at runtime? (see the last line of code below)

public class BootStrapper { Type baseTypeGeneric = typeof(Sample<>); public void BootStrap(Container container) { var types = from type in Assembly.GetExecutingAssembly().GetTypes() where type.Namespace == "NS.xyz" select type; foreach (Type type in types) { Type baseType = baseTypeGeneric.MakeGenericType(type); if (type.BaseType == baseType) { container.Register(type); } //how do I get this line to work? container.RegisterInitializer<Sample<[type]>>( x => container.InjectProperties(x)); } } } 
+4
source share
1 answer

The solution is actually quite simple: implement a non-generic interface on Sample<T> . This allows you to simply register one delegate for all sample types:

 public interface ISample { } public abstract class Sample<T> : ISample { } public void Bootstrapper(Container container) { container.RegisterInitializer<ISample>( instance => container.InjectProperties(instance)); } 

Since RegisterInitializer will be used for all types that implement ISample , you just need one registration.

But, to be honest, you have to be very careful with the injection of properties, as this leads to a container configuration that is difficult to verify. When dependencies are entered into constructors, the container will throw an exception when there is no dependency. On the other hand, with the introduction of properties, a missing dependency is simply skipped, and no exception is thrown. For this reason, the InjectProperties method is deprecated in version 2.6. Review your strategy. Perhaps you should reconsider. If you have doubts and how some feedback on your design; post a new question here at Stackoverflow.

+3
source

All Articles