ipjohnson / Grace

Grace is a feature rich dependency injection container library
MIT License
336 stars 33 forks source link

Bulk registration of open generics #148

Closed davidkeaveny closed 6 years ago

davidkeaveny commented 6 years ago

I am writing a WebAPI that uses CQRS, and I want to be able to register all implementations of CommandHandler<T> in a set of given assemblies. It looks like open generic registration is implemented like this:

registrations.Export(typeof(CommandHandler<>))
    .As(typeof(ICommandHandler<>));

Am I heading in the right direction, and how can I auto-register all implementations of CommandHandler<T> in a given set of assemblies?

Update : actually, the above doesn't work in my situation; CommandHandler<T> is an abstract base class used by the actual command handlers, and as such it has a protected constructor with a single parameter. Grace complains that the class doesn't have a public constructor, and fails the resolution. If I register individual command handlers individually, then everything works fine.

ipjohnson commented 6 years ago

Hi @davidkeaveny

You are correct Grace is interpreting that to mean please export the type CommandHandler<> which as you say is abstract and can't be created. Grace does have a bulk registration feature that works on an enumeration of types as well as some helper extension methods for use like ExportAssemblyContaining<T>.

For the moment it looks like you can register your commands like this.

registrations.Export(YourAssembly.ExportedTypes).BasedOn(typeof(CommandHandler<>)).ByInterfaces();

Normally I would suggest the syntax below but it seems there is a small bug in the bulk registration for ByInterface when doing generic interfaces (it exports only open generic implementations currently). I'm going to check in a fix for this right now but it won't be available till next release.

registrations.Export(YourAssembly.ExportedTypes).ByInterface(typeof(ICommandHandler<>));
davidkeaveny commented 6 years ago

Thanks, your provided code sample works just fine for me.

I'll look out for the ByInterface fix when it comes.

ipjohnson commented 6 years ago

@davidkeaveny I'm going to close this out and plan to do a release in the next couple days. If you have any other issue let me know.