[英]How to scan for all implementations of a generic type with Ninject
We are using the domain events pattern and leaning on our IoC container to locate handlers for a particular type of event: 我们使用域事件模式并依靠我们的IoC容器来定位特定类型事件的处理程序:
public interface IHandleEvent<TEvent> where TEvent : IEvent
{
void Handle(TEvent evnt);
}
With StructureMap we can scan and register all types implementing the above interface like so: 使用StructureMap,我们可以扫描并注册实现上述接口的所有类型,如下所示:
Scan(cfg =>
{
cfg.TheCallingAssembly();
cfg.ConnectImplementationsToTypesClosing(typeof(IHandleEvent<>));
});
Is there an equivalent with Ninject? 是否与Ninject相当?
Currently I'm having to bind each handler individually like so: 目前我必须单独绑定每个处理程序,如下所示:
kernel.Bind<IHandleEvent<SomeEvent>>().To<EventHandler1>();
kernel.Bind<IHandleEvent<SomeEvent>>().To<EventHandler2>();
kernel.Bind<IHandleEvent<SomeOtherEvent>>().To<EventHandler3>();
The Ninject Conventions Extensions package did exactly what I need. Ninject Conventions Extensions包完全符合我的需要。 The working code is below:
工作代码如下:
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses().InheritedFrom(typeof(IHandleEvent<>))
.BindSingleInterface());
Try Ninject Conventions Extensions . 试试Ninject Conventions Extensions 。 It provides a configuration by convention for Ninject.
它按照惯例为Ninject提供配置。 There is quite good documentation in wiki.
在wiki中有很好的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.