Automatically bind interfaces using AutoFac Automatically bind interfaces using AutoFac asp.net asp.net

Automatically bind interfaces using AutoFac


I'm not a AutoFac experienced user. However after some research a tested the code below with success:

var assembly = Assembly.GetExecutingAssembly();builder    .RegisterAssemblyTypes(assembly)    .AssignableTo<IQuery>()    .AsImplementedInterfaces()    .InstancePerRequest();

The IQuery interface above is just a tag interface that should be inherited from every query interface that you have. Using your example:

Interfaces

IUserQuery: IQueryICustomerQuery: IQuery

Classes

UserQuery: IUserQueryCustomerQuery: CustomerQuery


You need to use the assembly scanning feature of Autofac.

If your interfaces or your implementations are sharing a base class (e.g QueryBase) or a base interface (e.g. IQuery) then you can use the convince methods for the registration like: AssignableTo<>, etc. see gustavodidomenico's answer.

However sometimes you can't have a common base interface/class in that case you can use the Where method where you can have any custom logic for detecting which classes should be registered and how.

In that case your registration should roughly look like this:

builder.RegisterAssemblyTypes(yourAssembly)       .Where(t => t.IsClass && t.Name.EndsWith("Query"))       .As(t => t.GetInterfaces().Single(i => i.Name.EndsWith(t.Name)));

It will register all the types from a given assembly which name ends with "Query" with the matching interface, so it will register SomeNiceQuery with the interface ISomeNiceQuery


Alternatively, you can just register each type as either it's first implemented interface or it's own self.

builder.RegisterAssemblyTypes(new[] { Assembly.GetAssembly(typeof(IUserQuery))})        .Where(x=> x.IsClass && x.Name.EndsWith("Query"))        .As(t => t.GetInterfaces().Any() ? t.GetInterfaces()[0] : t);