我正在使用Scrutor在实现接口的程序集中注册所有类型。但是,我想排除继承实现接口的非抽象类型的类型。
我的代码结构类似于以下内容(为简洁起见,所有类型成员均省略:]
interface IBar {}
interface IFoobar : IBar {}
class Bar : IBar {}
class Foobar : Bar, IFoobar {}
在Startup.ConfigureServices
中:
services.Scan(s => s.FromCallingAssembly().AddClasses(false).AsImplementedInterfaces());
这将导致IBar
的两个注册,一个注册的实现类型为Bar
,一个注册的实现类型为Foobar
。我想要的是获得的一个IFoobar
注册(解析为Foobar
),但是只有一个注册IBar
分解为Bar
。
[Foobar
源自Bar
,因为它需要Bar
中的功能,而IFoobar
扩展IBar
。
是否有办法确保接口只向直接继承该接口的类注册一次,而不是通过基类注册一次?
我根据RegistrationStrategy
使用here来解决这个问题(链接错误地称它为ReplacementStrategy
)。我只搜索并注册一个匹配的接口after首先注册所有实现的接口,但使用“全部替换” RegistrationStrategy
。
services.Scan(s => s
.FromCallingAssembly()
.AddClasses(false)
.AsImplementedInterfaces()
.UsingRegistrationStrategy(RegistrationStrategy.Replace(ReplacementBehavior.All))
.AsMatchingInterface());
这完成了任务!