首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >批量注册开放通用实现

批量注册开放通用实现
EN

Stack Overflow用户
提问于 2017-08-14 14:05:56
回答 1查看 310关注 0票数 4

我正在尝试以一种未来的方式编写我的合成根,这样当我添加更多使用SimpleInjector 4实现基本实体的命令时,它们会自动被拾取。

域类如下所示:

代码语言:javascript
复制
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控制器使用命令处理程序,如下所示:

代码语言:javascript
复制
// With base entity
private ICommandHandler<UpdateCommand<BlogEntry>> updateBlogEntryCommandHandler;
// Without base entity
private ICommandHandler<AddBlogEntryCommentCommand> addBlogEntryCommentCommandHandler;

我的组成根如下所示:

代码语言:javascript
复制
// 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类似,但它不能回答我的问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-14 14:44:11

您可以使用它们的开放泛型类型来注册它们,而不是逐个为您的开放泛型实现的封闭泛型版本进行所有注册:

代码语言:javascript
复制
container.Register(typeof(ICommandHandler<>), typeof(DeleteCommandHandler<>));
container.Register(typeof(ICommandHandler<>), typeof(UpdateCommandHandler<>));

Simple Injector将自动为您关闭这些类型。只有当添加新的泛型实现时,您才必须将其作为注册添加到yuor Composition中。

如果您希望添加许多泛型类型,则可以使用以下代码一次注册所有实现:

代码语言:javascript
复制
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>)不允许将开放泛型类型传递到类型列表中。这就是为什么你必须(现在)单独注册泛型类型。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45668304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档