wireup icon indicating copy to clipboard operation
wireup copied to clipboard

Add option to inject all services implementing a given interface

Open maldoinc opened this issue 1 year ago • 3 comments

Users should have the option to inject everything that implements some interface or protocol(once they get added).

maldoinc avatar May 04 '24 22:05 maldoinc

Could you add some examples of what this issue wants to achieve? That would be super helpful.

smokyabdulrahman avatar Apr 20 '25 11:04 smokyabdulrahman

There's a few issues of things I imagined would be useful but haven't fully scoped. This being one of them. I always imagined some sort of services: Annotated[List[ServiceInterface], Inject(supports=ServiceInterface]) but it does need some scoping.

maldoinc avatar Apr 20 '25 16:04 maldoinc

The target api is as follows:

def main(
    all_caches: Injected[Set[T]], # This injects a set of all Cache implementations
    all_caches_map: Injected[Mapping[Hashable, T]] # Inject a map<qualifier,
): ...
@abstract
class Cache: ...


@service(qualifier="redis")
class RedisCache(Cache): ...


@service(qualifier="in_memory")
class InMemoryCache(Cache): ...

container = wireup.create_sync_container(service_modules=[importlib.import_module(__name__)])


@wireup.inject_from_container(container)
def main(all_caches: Injected[Set[Cache]], all_caches_map: Injected[Mapping[str, Cache]]):
    for cache in all_caches:
        print(f"Cache: {cache}")

    for name, cache in all_caches_map.items():
        print(f"Cache '{name}': {cache}")


main()

Internally this can be implemented in the registry as a new service for each interface, that creates a function and registers it with itself returning the set/dict containing the impls in _extend_with_services.

maldoinc avatar Aug 28 '25 20:08 maldoinc