I am using Simple Injector because it is really easy to assign a bunch of generic interfaces to their concretions. I have run into a roadblock though when my generics are two levels deep. I was hoping that there is a simple solution to this I haven't thought of. Here is an example of manually hooking up a single dependency:
container
.Register<ICommandHandler<UpdateCommand<Schools>>, UpdateCommandHandler<Schools>>();
This is what I would like to do instead:
container.Register(typeof(ICommandHandler<UpdateCommand<>>), modelAssembly);
but that does not compile.
the Register
Auto-Registration API skips open-generic implementations, such as UpdateCommandHandler<T>
, because these types typically need special handling. Instead, Register
will only select non-generic implementations.
To register this open-generic implementation, you will have to register it explicitly:
container.Register(typeof(ICommandHandler<>), typeof(UpdateCommandHandler<>));
Alternatively, in case you have many open-generic implementations that can be registered in any particular order, you can Auto-Register all non-generic and open-generic implementations (excluding decorators) as follows:
var handlerTypes =
container.GetTypesToRegister(typeof(ICommandHandler<>), new[] { modelAssembly },
new TypesToRegisterOptions { IncludeGenericTypeDefinitions = true });
container.Register(typeof(ICommandHandler<>), handlerTypes);