Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 985
Karl Avatar asked Aug 16 '13 00:08

Karl


People also ask

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.

Which of the following option is used in automatic types of registration in order to scan an assembly and automatically register its types by convention?

Use Autofac as an IoC container API Web API project with the types you will want to inject. Autofac also has a feature to scan assemblies and register types by name conventions.

What is AsImplementedInterfaces?

RegistrationExtensions. AsImplementedInterfaces MethodSpecifies that a type from a scanned assembly is registered as providing all of its implemented interfaces.

What is Autofac C#?

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.


1 Answers

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<>));
like image 140
Steven Avatar answered Nov 14 '22 18:11

Steven