Skip to content

thomhurst/EnumerableServiceDecorator

Repository files navigation

EnumerableServiceDecorator

Call all IEnumerable<T> by calling a single injected T

nuget

Codacy Badge

CodeFactor

Support

If you like this library, consider buying me a coffee.

Buy Me A Coffee

Usage

  1. Register multiple implementations of your interfaces(s)
services.AddSingleton<IMyInterface, MyImplementation1>()
    .AddSingleton<IMyInterface, MyImplementation2>()
    .AddSingleton<IMyInterface, MyImplementation3>();
  1. After all your dependencies have been added (so at the END - the order matters!) call FlattenEnumerableToSingle<T>
        services.FlattenEnumerableToSingle<IMyInterface>()
  1. Inject just one T into your class
public class MyWorker
{
  private readonly IMyInterface _myInterface;
  
  public MyWorker(IMyInterface myInterface)
  {
    _myInterface = myInterface;
  }
}
  1. 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();
  1. Enjoy!

Caveats

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.

About

Call all IEnumerable<T> by calling a single injected T

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages