Feature Request: new Validate method
We all know once you've started using container you move some errors from compile time to runtime. So, it would be so cool to have a method in the container that validates that all dependencies could actually be resolved. So it could:
- Validate there is no cyclic dependencies
- There are public constructors in the registered types
- Validate there is no missing dependencies
I have actually thought about such a method. It is important to remember that the Validate method would also be a runtime check although you would probably fail faster this way which is a good thing, There is also the issue with captive dependencies. For instance transient services being injected into singletons should also be avoided.
We could probably build this as an extension using the AvailableServices property that contains all the registered services.
The Validate method could
- Try to detect captive dependencies Not all captive dependencies can be discovered though, since services can be registered using a factory delegate and that just represents code we can't really analyze. For implicit services registrations, this should provide great value.
- Loop through all registered services and try to resolve them This would detect cyclic dependencies, visibility on constructors and missing dependencies in a trial and error fashion
Something like this
public static void Validate(this ServiceContainer serviceContainer)
{
// Try to resolve all services
foreach (var serviceRegistration in serviceContainer.AvailableServices)
{
serviceContainer.GetInstance(serviceRegistration.ServiceType, serviceRegistration.ServiceName);
}
foreach (var serviceRegistration in serviceContainer.AvailableServices)
{
if (serviceRegistration.ImplementingType != null)
{
var constructor = serviceContainer.ConstructorSelector.Execute(serviceRegistration.ImplementingType);
var parameters = constructor.GetParameters();
//.. Do more validation stuff here
}
}
}
}
Interesting how it is done and what ir actually does in the DryIoc
@tom3m, Basically, DryIoc builds the expressions for specified resolution roots, catches the exceptions, and returns map between service registrations and raised exceptions.