Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/mustaddon/contravariancedependencyinjection

Contravariant and Covariant injection for Microsoft.Extensions.DependencyInjection
https://github.com/mustaddon/contravariancedependencyinjection

contravariance contravariance-dependency-injection contravariance-di contravariant covariance covariant dependency-injection dependency-injection-container proxy-pattern service-collection service-provider virtual-proxy

Last synced: 29 days ago
JSON representation

Contravariant and Covariant injection for Microsoft.Extensions.DependencyInjection

Awesome Lists containing this project

README

        

# ContravarianceDependencyInjection [![NuGet version](https://badge.fury.io/nu/ContravarianceDependencyInjection.svg?7)](http://badge.fury.io/nu/ContravarianceDependencyInjection)
Contravariant and Covariant injection for Microsoft.Extensions.DependencyInjection using the [Proxy pattern](https://en.wikipedia.org/wiki/Proxy_pattern).

### Example
```C#
interface IExampleContravariant
{
object? MyMethod(T request);
}
```
```C#
var services = new ServiceCollection()
.AddTransient, ExampleService>()
.AddTransient, ExampleService>()
.AddTransient, ExampleService>()

// REQUIRED: Adds contravariance injection for registred services IExampleContravariant
.AddContravariance(typeof(IExampleContravariant<>), SearchStrategy.MaxCloser)

.BuildServiceProvider();

// inheritance example contracts
// ContractBase -> ContractA -> ContractAB -> ContractABC
// ContractBase -> ContractB

// IExampleContravariant is not registered,
// IExampleContravariant is invoked instead
Console.WriteLine(" Result: " +
services.GetRequiredService>()
.MyMethod(new ContractABC()));

// IExampleContravariant is not registered,
// IExampleContravariant is invoked instead
Console.WriteLine(" Result: " +
services.GetRequiredService>()
.MyMethod(new ContractB()));
```

[Program.cs](https://github.com/mustaddon/ContravarianceDependencyInjection/blob/main/Example/Program.cs)

### Concept

[](https://app.dgrm.net/?u=https://raw.githubusercontent.com/mustaddon/ContravarianceDependencyInjection/master/dgrm.png)