How to register many for open generic in Autofac
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();
Related videos on Youtube
amiry jd
My other SO-Profile: https://stackoverflow.com/users/974276/j-amiry I am a hard-working and innovative developer with near 18 years of experience mostly based on .NET (Framework & Core) technology stack. For the last few years, alongside developing some awesome applications, I was focused on some non-coding tasks such as building up development teams, team leading, tech leading, problem solving, consulting, architecting, reviewing other's code, and mentoring. As a self-motivated fast-learner experienced code-guy, who has a proactive personality to step up to new challenges, I think I'm the man who can get the job done.
Updated on December 16, 2020Comments
-
amiry jd over 3 years
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?
-
amiry jd almost 11 yearsSorry ): I'm working with @Javad_Amiry's team (Kavand). That is because of the problem Javad_Amiry asked before (here and on codeplex). Unfortunately in this project we cannot use simple injector. But our main DI lib still is SimpleInjector. We used it in many projects and we'll continue using it. :)
-