3

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

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

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

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,但这似乎不适用于开放通用接口的开放通用实现。

我尝试过的事情:

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();

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

提前致谢

4

1 回答 1

4

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

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(...)我想如果你愿意的话,你可以做类似的事情。

于 2018-05-23T21:55:02.970 回答