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?

有帮助吗?

解决方案

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.

其他提示

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<>))));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top