我正在尝试以一种未来的方式编写我的合成根,这样当我添加更多使用SimpleInjector 4实现基本实体的命令时,它们会自动被拾取。
域类如下所示:
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 { . . . }然后我的API控制器使用命令处理程序,如下所示:
// With base entity
private ICommandHandler<UpdateCommand<BlogEntry>> updateBlogEntryCommandHandler;
// Without base entity
private ICommandHandler<AddBlogEntryCommentCommand> addBlogEntryCommentCommandHandler;我的组成根如下所示:
// 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>>();注意:这与Simple Injector usage for generic command handler类似,但它不能回答我的问题。
发布于 2017-08-14 14:44:11
您可以使用它们的开放泛型类型来注册它们,而不是逐个为您的开放泛型实现的封闭泛型版本进行所有注册:
container.Register(typeof(ICommandHandler<>), typeof(DeleteCommandHandler<>));
container.Register(typeof(ICommandHandler<>), typeof(UpdateCommandHandler<>));Simple Injector将自动为您关闭这些类型。只有当添加新的泛型实现时,您才必须将其作为注册添加到yuor Composition中。
如果您希望添加许多泛型类型,则可以使用以下代码一次注册所有实现:
var types = container.GetTypesToRegister(typeof(ICommandHandler<>),
new[] { typeof(ICommandHandler<>).Assembly },
new TypesToRegisterOptions { IncludeGenericTypeDefinitions = true });
container.Register(typeof(ICommandHandler<>),
types.Where(t => !t.IsGenericTypeDefinition));
foreach (Type type in types.Where(t => t.IsGenericTypeDefinition))
{
container.Register(typeof(ICommandHandler<>), type);
}由于v4.0中的Register限制(即V4.1中的planned to get fixed ),Register(Type, IEnumerable<Type>)不允许将开放泛型类型传递到类型列表中。这就是为什么你必须(现在)单独注册泛型类型。
https://stackoverflow.com/questions/45668304
复制相似问题