I like to make my life easier. If I can automate a process, I’d love to do it. It is no different in programming. Today I would like to show you how to automate dependency registration in DI container.

Manual dependency registration

For example, we have a set of dependencies to register:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddTransient<ICommandHandler<CreateUserCommand>, CreateUserCommandHandler>()
        .AddTransient<ICommandHandler<DeleteUserCommand>, DeleteUserCommandHandler>()
        .AddTransient<ICommandHandler<AddUserPostCommand>, AddUserPostCommandHandler>()
        .AddTransient<IQueryHandler<GetUserQuery, User>, GetUserQueryHandler>()
        .AddTransient<IQueryHandler<GetUserPostQuery, Post>, GetUserPostQueryHandler>();
}

It is not difficult to imagine a scenario where there will be many more dependencies to register. Luckily, there’s an easy way to automate this!

Automation with Scrutor

Let me introduce you to Scrutor. It is a small but powerful library that allows automatic assembly scanning and dependency registration. It is actually an IServiceCollection extensions set.

The following code does exactly the same as the previous example, except that it does it automatically.

public void ConfigureServices(IServiceCollection services)
{
    services.Scan(scan => scan
        .FromAssemblyOf<CreateUserCommand>() // Indicates the assembly where all dependencies are located 
            .AddClasses(classes => classes.AssignableTo(typeof(ICommandHandler<>))) // Register all command handlers
                .AsImplementedInterfaces() // We will be able to resolve them by their interfaces
                .WithTransientLifetime() // Scope definition
            .AddClasses(classes => classes.AssignableTo(typeof(IQueryHandler<,>)))
                .AsImplementedInterfaces()
                .WithTransientLifetime());
}

Now you won’t have to remember to register another dependency. Super handy, huh?

Concluding

In conclusion, it’s worth using Scrutor. Hope you find it useful and save you a lot of time. I encourage you to read its documentation and learn about its other capabilities.

Do you automate any boring and repetitive stuff? Let me know!