I have the following interfaces:
public interface IValidator
{
Task<Response> Validate(object request);
}
public interface IFirstChildValidator : IValidator
public interface ISecondChildValidator : IValidator
I have some services that implement the first and the second validators.
Before using Scrutor, I registered the services manually, and everything worked as expected:
services.AddScoped<IFirstChildValidator, FirstBar>();
services.AddScoped<IFirstChildValidator, FirstFoo>();
services.AddScoped<ISecondChildValidator, SecondBar>();
services.AddScoped<ISecondChildValidator, SecondFoo>();
and I could inject a specific validator to my other services:
private readonly IEnumerable<IFristValidator> _firstValidators;
// ctor injection
However, when I try to auto-register (the first validator as an example) using Scrutor:
services.Scan(scan => scan
.FromAssemblyOf<IFirstChildValidator >()
.AddClasses(classes => classes
.InNamespaces("my.namespace")
.AssignableTo<IFirstChildValidator>())
.UsingRegistrationStrategy(RegistrationStrategy.Replace(ReplacementBehavior.ImplementationType))
.AsImplementedInterfaces()
.WithScopedLifetim();
The injected type is the parent validator (i.e. IValidator
), and the injected array of the specific implementation is left empty.
How can I achieve auto-register as specific interfaces as types?
You must remove the UsingRegistrationStrategy
this defines how to handle duplicates, in your case you want ALL of its implementations.
You can also replace it with .UsingRegistrationStrategy(RegistrationStrategy.Append)
services.Scan(scan => scan
.FromAssemblyOf<IFirstChildValidator>()
.AddClasses(classes => classes
.InNamespaces("my.namespace")
.AssignableTo<IFirstChildValidator>())
.AsImplementedInterfaces()
.WithScopedLifetime());
Here a .NET FIddle