Register interface only with class that directly inherits it in Scrutor

1.7k Views Asked by At

I'm using Scrutor to register all types in my assembly that implement interfaces. However, I want to exclude types that inherit non-abstract types that implement an interface.

I have a code structure similar to the following (all type members omitted for brevity):

interface IBar {}

interface IFoobar : IBar {}

class Bar : IBar {}

class Foobar : Bar, IFoobar {}

In Startup.ConfigureServices:

services.Scan(s => s.FromCallingAssembly().AddClasses(false).AsImplementedInterfaces());

This results in two registrations for IBar, one with implementation type Bar and one with implementation type Foobar. What I want is one registration for IFoobar (resolves to Foobar) which I get, but just one registration for IBar which resolves to Bar.

Foobar derives from Bar because it requires functionality in Bar while IFoobar extends IBar.

Is there a way to ensure that an interface is only registered once with the class that inherits it directly and not via base classes?

1

There are 1 best solutions below

0
Neo On BEST ANSWER

I figured this out using a RegistrationStrategy as per here (the link wrongly calls it ReplacementStrategy). I simply search for and register a matching interface after registering all implemented interfaces first, but using a 'replace by implementation type' RegistrationStrategy.

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

This does the job!