Question

I am using ASP.NET MVC 5. I am new to AutoFac. I have lot of classes and for each class I have to do,

builder.RegisterType<AuthenticationService>().As<IAuthenticationService>();
builder.RegisterType<IAuthenticationRepositry>().As<AuthenticationRepositry>();
...............................................................................
...............................................................................

Registering each type is time-consuming and quite easily forget-able. Is there is any automatic way to register components in AutoFac?

Was it helpful?

Solution

If you want to automatically register all types as their interfaces, you can use RegisterAssemblyTypes:

builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).AsImplementedInterfaces();

Or AsSelf, if you want to resolve concrete implementations.

OTHER TIPS

Your XXXService and XXXRepository classes will likely violate the SOLID principles (such as SRP, OCP, and ISP). Try hiding business logic and repository logic behind generic abstractions as can be learned here and here. This makes it easy to add cross-cutting concerns to these classes and allows you to register each group in a single line of code:

builder.RegisterAssemblyTypes(assemblies)
    .As(t => t.GetInterfaces()
    .Where(a => a.IsClosedTypeOf(typeof(ICommandHandler<>))));

builder.RegisterAssemblyTypes(assemblies)
    .As(t => t.GetInterfaces()
    .Where(a => a.IsClosedTypeOf(typeof(IQueryHandler<>))));

builder.RegisterAssemblyTypes(assemblies)
    .As(t => t.GetInterfaces()
    .Where(a => a.IsClosedTypeOf(typeof(IRepository<>))));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top