Skip to content

Contravariant and Covariant injection for Microsoft.Extensions.DependencyInjection

License

Notifications You must be signed in to change notification settings

mustaddon/ContravarianceDependencyInjection

Repository files navigation

ContravarianceDependencyInjection NuGet version

Contravariant and Covariant injection for Microsoft.Extensions.DependencyInjection using the Proxy pattern.

Example

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()));

Program.cs

Concept