Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac test all registered types can be resolved

Tags:

c#

autofac

I have a bunch of types registered with Autofac and some of the dependencies are rather deep. Is there a built in way to test that I can resolve all registered types? I want to fail fast at application startup, and not several minutes later part way in.

This is what I'm currently doing, and it seems to work, but I still wonder if there isn't a better way.

    public void VerifyAllRegistrations()
    {
        foreach (IComponentRegistration registration in _container.ComponentRegistrations)
        {
            bool isNewInstance;
            registration.ResolveInstance(_container, new Parameter[0], new Disposer(), out isNewInstance);
        }            
    }

    private class Disposer : IDisposer
    {
        public void Dispose()
        {
            // no-op
        }

        public void AddInstanceForDisposal(IDisposable instance)
        {
            instance.Dispose();
        }
    }
like image 608
Sneal Avatar asked Jul 30 '09 00:07

Sneal


People also ask

How does Autofac resolve?

When resolving a service, Autofac will automatically chain down the entire dependency hierarchy of the service and resolve any dependencies required to fully construct the service.

How do I register an Autofac service?

Register by Type var builder = new ContainerBuilder(); builder. RegisterType<ConsoleLogger>(); builder. RegisterType(typeof(ConfigReader)); When using reflection-based components, Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container.

What is Autofac container?

Autofac is an addictive IoC container for . NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular . NET classes as components.

How do I get Autofac containers?

From Visual Studio, you can get it via NuGet. The package name is Autofac. Alternatively, the NuGet package can be downloaded from the GitHub repository (https://github.com/autofac/Autofac/releases).


1 Answers

Autofac doesn't offer anything to that effect - because Autofac creates components in response to ResolveInstance, you're going to be faced with constructor side-effects etc.

Integration testing is the best way to address this.

like image 82
Nicholas Blumhardt Avatar answered Sep 30 '22 13:09

Nicholas Blumhardt