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?
You need to exactly write like this: builder. RegisterGeneric(typeof(RepositoryBase<>)) . As(typeof(IRepository<>)); note the empty <> and it will register your Repository for all of your entites.
You register components with Autofac by creating a ContainerBuilder and informing the builder which components expose which services. Components can be created via reflection (by registering a specific .
From Visual Studio, you can get it via NuGet. The package name is Autofac. Alternatively, the NuGet package can be downloaded from the GitHub repository (https://github.com/autofac/Autofac/releases).
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();
If you have a single concrete generic type, and don't want the scanning overhead and improve the startup performance, you can register as below:
builder.RegisterGeneric(typeof(ConcreteGenericType<>)).As(typeof(IServiceType<>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With