c# - 如何使用 Autofac 注册开放通用接口(interface)的所有实现

标签 c# dependency-injection inversion-of-control autofac open-generics

我目前有一个用于管道中单个步骤的界面。

public interface IPipelineStep<T1, T2>
  where T1: ModelObject
  where T2: EntityObject { }

我有一大堆实现这个接口(interface)的步骤:

public class ValidateModelStep<T1, T2> : IPipelineStep<T1, T2>
  where T1: ModelObject
  where T2: EntityObject { }

public class Step2<T1, T2> : IPipelineStep<T1, T2>
  where T1: ModelObject
  where T2: EntityObject { }

public class Step3<T1, T2> : IPipelineStep<T1, T2>
  where T1: ModelObject
  where T2: EntityObject { }

public class Step4<T1, T2> : IPipelineStep<T1, T2>
  where T1: ModelObject
  where T2: EntityObject { }

我目前正在这样注册它们:

builder.RegisterGeneric(typeof(ValidateModelStep<,>)).As(typeof(IPipelineStep<,>)).AsSelf();
builder.RegisterGeneric(typeof(Step2<,>)).As(typeof(IPipelineStep<,>)).AsSelf();
builder.RegisterGeneric(typeof(Step3<,>)).As(typeof(IPipelineStep<,>)).AsSelf();
builder.RegisterGeneric(typeof(Step4<,>)).As(typeof(IPipelineStep<,>)).AsSelf();

然后我可以使用 autofac 来实例化这些步骤。问题是,我有很多很多步骤。每次我创建一个新的时都必须注册每个,这非常令人沮丧。

有什么方法可以一次全部注册吗?

我知道您可以使用程序集扫描和 AsClosedTypesOf,但这似乎不适用于开放通用接口(interface)的开放通用实现。

我尝试过的事情:

builder.RegisterAssemblyTypes(myAssembly).AsClosedTypesOf(typeof(IPipelineStep<,>)).AsImplementedInterfaces();

builder.RegisterAssemblyTypes(myAssembly).AssignableTo(typeof(IPipelineStep<,>)).As(typeof(IPipelineStep<,>)).AsSelf();

builder.RegisterAssemblyTypes(myAssembly)
.Where(t => t.IsAssignableFrom(typeof(IPipelineStep<,>)))
.As(typeof(IPipelineStep<,>)).AsSelf();

当接口(interface)的实现还必须包含泛型时,有什么方法可以使用 AsClosedTypesOf 吗?

提前致谢

最佳答案

我想最直接的方法是自己扫描程序集:

foreach (var t in myAssembly.GetTypes()
    .Where(c => !c.IsInterface && c.IsGenericTypeDefinition && c.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IPipelineStep<,>)))) {
    builder.RegisterGeneric(t).As(typeof(IPipelineStep<,>)).AsSelf();
}

这基本上过滤了开放通用的类型并实现了 IPipelineStep<> ,然后注册到容器中。我想你可以用 RegisterAssemblyTypes.Where(...) 做类似的事情如果您愿意。

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

相关文章:

c# - MeasureOverride 和 ArrangeOverride 在 Windows Server 2016 上的执行速度比 Windows 10 专业版慢 3 倍

C# Big-endian ulong 来自 4 个字节

c# - 拆分 - 索引超出数组范围

c# - 使用 StructureMap 将接口(interface)注入(inject)重载类构造函数

inversion-of-control - SimpleIoc.Default.GetInstance 和 ServiceLocator.Current.GetInstance 之间有区别吗

c# - 应用程序滞后于每个计时器滴答

java - 覆盖 Micronaut 测试中的依赖项

dependency-injection - casperjs:如何在单元测试期间在测试本身中包含其他 javascript 文件?

Bootstrap 中的 Angular2 提供程序与 @component

c# - 结构图范围/生命周期指南?