How to register many for open generic in Autofac

一笑奈何 提交于 2019-12-03 08:24:32

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/16757945/how-to-register-many-for-open-generic-in-autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!