Call all IEnumerable<T> by calling a single injected T
If you like this library, consider buying me a coffee.
- Register multiple implementations of your interfaces(s)
services.AddSingleton<IMyInterface, MyImplementation1>()
.AddSingleton<IMyInterface, MyImplementation2>()
.AddSingleton<IMyInterface, MyImplementation3>();
- After all your dependencies have been added (so at the END - the order matters!) call
FlattenEnumerableToSingle<T>
services.FlattenEnumerableToSingle<IMyInterface>()
- Inject just one
T
into your class
public class MyWorker
{
private readonly IMyInterface _myInterface;
public MyWorker(IMyInterface myInterface)
{
_myInterface = myInterface;
}
}
- Call a method on your interface. It'll automagically call the same method in all of your registered classes
_myInterface.DoSomething();
await _myInterface.DoSomethingElseAsync();
The above will essentially do:
MyImplementation1.DoSomething();
MyImplementation2.DoSomething();
MyImplementation3.DoSomething();
await MyImplementation1.DoSomethingElseAsync();
await MyImplementation2.DoSomethingElseAsync();
await MyImplementation3.DoSomethingElseAsync();
- Enjoy!
The type to be flattened must be an interface.
This doesn't support Properties in your interfaces. There's no way to return multiple implementations of a property in just a single property.
The same with methods with return types. We can't turn an IEnumerable into a T.
So we can only support interfaces with methods that return void or Task.