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?
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.
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.
RegistrationExtensions. AsImplementedInterfaces MethodSpecifies that a type from a scanned assembly is registered as providing all of its implemented interfaces.
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.
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<>));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With