Search code examples
dependency-injectionioc-containerautofac

How to register Services and Types that are in separate assemblies in Autofac?


I'm trying to register my 'services' with Autofac. The services are named based on convention (Aggregate Root + 'Service') and all implement interfaces with the same name: 'I' + ServiceName. For example, OrderService implements IOrderService.

However, both the concrete types and interfaces are in separate assemblies. So far I have the following code:

builder.RegisterAssemblyTypes(typeof(OrderService).Assembly)
       .Where(t => t.Name.EndsWith("Service"))
       .AsImplementedInterfaces();

Is this the best way to accomplish this in Autofac? What if some of my services derive from abstract class?


Solution

  • Autofac doesn't care whether those interfaces are in the same assembly or not. So your registration does just fine, but if you want to load 'services' from several assemblies, you can just pass in a collection of assemblies:

    builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
       .Where(t => t.Name.EndsWith("Service"))
       .AsImplementedInterfaces();
    

    I like to warn you about certain class postfixes that indicate SRP violations, and RAP violations such as Helper, Manager, and... Service. You might want to try a different design where each query and use case of such a service class is placed in its own class and marked with a generic interface. This way you can register all implementations of the same generic interface with one single line:

    builder.RegisterAssemblyTypes(
        AppDomain.CurrentDomain.GetAssemblies())
        .AsClosedTypesOf(typeof(ICommandHandler<>));