LightInject icon indicating copy to clipboard operation
LightInject copied to clipboard

Feature Request: new Validate method

Open yahorsi opened this issue 9 years ago • 3 comments

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:

  1. Validate there is no cyclic dependencies
  2. There are public constructors in the registered types
  3. Validate there is no missing dependencies

yahorsi avatar Sep 22 '16 10:09 yahorsi

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

  1. 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.
  2. 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 
                }    
            }            
        }
    }

seesharper avatar Sep 22 '16 10:09 seesharper

Interesting how it is done and what ir actually does in the DryIoc

yahorsi avatar Mar 22 '17 07:03 yahorsi

@tom3m, Basically, DryIoc builds the expressions for specified resolution roots, catches the exceptions, and returns map between service registrations and raised exceptions.

dadhi avatar Mar 22 '17 08:03 dadhi