我目前有一个用于管道中单个步骤的界面。
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/