c# - 使用 LightInject 注册所有实现通用接口(interface)的类

标签 c# dependency-injection inversion-of-control rebus light-inject

我不知道如何使用 LightInject 的 API 来注册给定类中定义的所有处理程序。在本例中,使用 LightInject 适配器为 Rebus 定义处理程序。

因此给定一个处理程序定义为:

public class MyHandler : IHandleMessages<MyMessage>
{
}

我想我可以按如下方式在程序集中注册所有内容:

container.RegisterAssembly(typeof(HandlerBase).Assembly,
    (s, Type) => Type.GetInterfaces().Contains(typeof(IHandleMessages<>)));

但是当我尝试注册该类型的实例时,找不到它们(container.AvailableServices 显示类型但 value 属性为 null)

var detectedHandlers = container.GetAllInstances<IHandleMessages<MyMessage>>();

有效的方法是手动定义它,如下所示:

container.Register<IHandleMessages<MyMessage>, MyHandler>();

但这并不理想,因为它需要手动注册。有没有办法用 LightInject 来做到这一点?

最佳答案

您的注册将不起作用,因为非泛型类型,例如 MyHandler永远不要实现开放通用抽象,例如 IHandleMessages<> 。相反,您应该检查是否 MyHandler实现 IHandleMessages<>封闭版本:

container.RegisterAssembly(typeof(HandlerBase).Assembly,
   (s, _) => s.IsGenericType && s.GetGenericTypeDefinition() == typeof(IHandleMessages<>));

请注意,之前的注册通过使用s进一步简化了注册。服务类型参数,这使您不必调用 .GetInterfaces() .

关于c# - 使用 LightInject 注册所有实现通用接口(interface)的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48780797/

相关文章:

c# - 如何在MVC4的Web API中设计非CRUD操作?

java - Jersey 2.0 的依赖注入(inject)

java - Autowiring 在 Spring 4 中不起作用

c# - configSource 绝对路径解决方法

c# - Xunit - 在少数全套测试中禁用并行性

Azure 耐用功能 : Can I use a startup. cs?

c# - 领域驱动设计 : access a configured value from an Entity without using a Service Locator

.net - 将 IOC 容器复古安装到 Brownfield Enterprise .net 应用程序

c# - 依赖注入(inject)组合根和装饰器模式

c# - 我可以关闭对我的代码引用的单个程序集的跟踪吗?