How to register many for open generic in Autofac

agent47 picture agent47 · May 26, 2013 · Viewed 10.9k times · Source

I'm new to Autofac (not to DI). Here is the situation:

I have these interfaces:

public interface IQuery<out TResult> : IQuery { }

public interface IQueryHandler<in TQuery, out TResult> where TQuery : IQuery<TResult> {
    TResult Handle(TQuery query);
}

and there is a lot of implementation of them in my solution:

class GetPersonQuery : IQuery<PersonModel> { }
class GetPersonQueryHandler : IQueryHandler<GetPersonQuery, PersonModel> { }

class GetArticleQuery : IQuery<ArticleModel> { }
class GetArticleQueryHandler : IQueryHandler<GetArticleQuery, ArticleModel> { }

class GetSomethingQuery : IQuery<IEnumerable<SomeModel>> { }
class GetSomethingQueryHandler : IQueryHandler<GetSomethingQuery, IEnumerable<SomeModel>> { }

and so on. I'm currently registering them like this:

builder.RegisterType<GetPersonQueryHandler>()
    .As<IQueryHandler<GetPersonQuery, PersonModel>>();

builder.RegisterType<GetArticleQueryHandler>()
    .As<IQueryHandler<GetArticleQuery, ArticleModel>>();

builder.RegisterType<GetSomethingQueryHandler>()
    .As<IQueryHandler<GetSomethingQuery, SomeModel>>();

// blah blah blah

As you can see, I have a many same registrations. In SimpleInjector (which I was using before), I could register all of them by a single line:

container.RegisterManyForOpenGeneric(
    typeof(IQueryHandler<,>),
    AppDomain.CurrentDomain.GetAssemblies());

Is it possible to do this stuff in Autofac?

Answer

nemesv picture nemesv · May 26, 2013

You can do this with Autofac you just need to use the scanning feature and use the AsClosedTypesOf method:

AsClosedTypesOf(open) - register types that are assignable to a closed instance of the open generic type.

So your registration will look like this:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
       .AsClosedTypesOf(typeof (IQueryHandler<,>)).AsImplementedInterfaces();