Contravariant and Covariant injection for Microsoft.Extensions.DependencyInjection using the Proxy pattern.
interface IExampleContravariant<in T>
{
object? MyMethod(T request);
}
var services = new ServiceCollection()
.AddTransient<IExampleContravariant<ContractBase>, ExampleService<ContractBase>>()
.AddTransient<IExampleContravariant<ContractAB>, ExampleService<ContractAB>>()
.AddTransient<IExampleContravariant<ContractA>, ExampleService<ContractA>>()
// REQUIRED: Adds contravariance injection for registred services IExampleContravariant
.AddContravariance(typeof(IExampleContravariant<>), SearchStrategy.MaxCloser)
.BuildServiceProvider();
// inheritance example contracts
// ContractBase -> ContractA -> ContractAB -> ContractABC
// ContractBase -> ContractB
// IExampleContravariant<ContractABC> is not registered,
// IExampleContravariant<ContractAB> is invoked instead
Console.WriteLine(" Result: " +
services.GetRequiredService<IExampleContravariant<ContractABC>>()
.MyMethod(new ContractABC()));
// IExampleContravariant<ContractB> is not registered,
// IExampleContravariant<ContractBase> is invoked instead
Console.WriteLine(" Result: " +
services.GetRequiredService<IExampleContravariant<ContractB>>()
.MyMethod(new ContractB()));