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));
}
}
}
The solution as actually rather simple: implement a non-generic interface on
Sample<T>. This allows you to just register a single delegate for all sample types:Since
RegisterInitializerwill be applied for all types that implementISample, you just need one registration.But to be honest, you should be very careful with applying property injection since this leads to container configuration that is hard to verify. When injecting dependencies into constructors, the container will throw an exception when a dependency is missing. With property injection on the other hand, a missing dependency is simply skipped and no exception is thrown. For this reason the InjectProperties method was deprecated in v2.6. Please review your strategy. Perhaps you should reconsider. If you are in doubt and like some feedback on your design; post a new question here at Stackoverflow.