2

我正在使用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因为它需要Barwhile IFoobarextends中的功能IBar

有没有办法确保接口只向直接继承它的类而不是通过基类注册一次?

4

1 回答 1

3

我使用RegistrationStrategyas per here解决了这个问题(链接错误地调用它ReplacementStrategy)。在首先注册所有实现的接口之后,我只需搜索并注册一个匹配的接口,但使用 'replace by implementation type' RegistrationStrategy

services.Scan(s => s
    .FromCallingAssembly()
    .AddClasses(false)
    .AsImplementedInterfaces()
    .UsingRegistrationStrategy(RegistrationStrategy.Replace(ReplacementBehavior.ImplementationType))
    .AsMatchingInterface());

这完成了工作!

于 2019-10-27T23:33:34.163 回答