Konda.eu

C# - Dependency Injections and Automatic Registration with Autofac

No comments

C# - Dependency Injections and Automatic Registration with Autofac

Dependency Injections are an awesome design pattern for adding a layer of abstraction into your application for various services and providers. Those can be quickly changed by registering another class and an instance is simply acquired by specifying desired interface as a parameter in constructor therefore decreasing or completely removing factory design pattern.

The only thing I find disturbing is whenever a new dependent class is added it must be registered with dependency injection provider, manual by default. As I consider everything that must be changed or added on a completely different place bad practice, I help myself with the following snippet of code:

var builder = new Autofac.ContainerBuilder();
var assembly = Assembly.GetExecutingAssembly();
var assemblyTypes = assembly.GetTypes();

foreach (var type in assemblyTypes)
{
    // Ignore interfaces
    if (type.IsInterface)
        continue;

    var typeInterfaces = type.GetInterfaces();

    // Class should implement IDependecy or ISingletonDependency
    if (!typeInterfaces.Any(i => i.IsAssignableFrom(typeof(IDependency))))
        continue;

    var registration = builder.RegisterType(type).AsImplementedInterfaces();

    if (typeInterfaces.Any(i => i.IsAssignableFrom(typeof(ISingletonDependency))))
        registration.SingleInstance();
    else
        registration.InstancePerRequest();
}

Where IDependency and ISingletonDependency are:

public interface IDependency {}

public interface ISingletonDependency : IDependency {}

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.