質問

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