Batch-registering open-generic implementations

Viewed 327

I'm trying to write my composition root in a future proof way so that when I add more commands that implement base entity with SimpleInjector 4 they automatically get picked up.

Domain classes look like this:

public interface ICommandHandler<TCommand> { . . . }

public class UpdateCommandHandler<T> : ICommandHandler<UpdateCommand<T>> 
    where T : EntityBase { . . . }

public class UpdateCommand<T> where T : EntityBase { . . . }

public abstract class EntityBase { . . . }

My API controllers then use command handlers as follows:

// With base entity
private ICommandHandler<UpdateCommand<BlogEntry>> updateBlogEntryCommandHandler;
// Without base entity
private ICommandHandler<AddBlogEntryCommentCommand> addBlogEntryCommentCommandHandler;

And my composition root looks like this:

// This works for all cases without as base entity e.g:
// private ICommandHandler<AddBlogEntryCommentCommand> addBlogEntryCommentCommandHandler;
container.Register(typeof(ICommandHandler<>), new[] { typeof(ICommandHandler<>).Assembly });


// And this works for when commands have a base entity but how do to I write it in a 
// generic, future-proof way like above?

container.Register<ICommandHandler<DeleteCommand<BlogEntryComment>>, DeleteCommandHandler<BlogEntryComment>>();
container.Register<ICommandHandler<UpdateCommand<BlogEntry>>, UpdateCommandHandler<BlogEntry>>();
container.Register<ICommandHandler<UpdateCommand<BlogEntryFile>>, UpdateCommandHandler<BlogEntryFile>>();

Note: this is a similar to Simple Injector usage for generic command handler but it does not answer my question.

1 Answers
Related