Skip to content

how to apply Decorator design pattern with rodi? #15

@Eldar1205

Description

@Eldar1205

Hi,
How to apply the Decorator design pattern with rodi, on single instance registrations and/or collection registrations?

Example how I used to do it with a DI container from C# .Net called SimpleInjector (if same syntax were to be in lagom):

class HttpClient(ABC):
    async def send(self, request: Request) -> Response:
        pass

class ActualHttpClient(HttpClient):
    async def send(self, request: Request) -> Response:
        # Implement actual request send, e.g. with aiohttp

class LoggingHttpClientDecorator(HttpClient):
    def __init__(self, decoratee: HttpClient):
        self.__decoratee = decoratee
    async def send(self, request: Request) -> Response:
        print("Sending request")
        response = await self.__decoratee.send(request);
        print("Received response")
        return response;

container = Container()
container[HttpClient] = Singleton(ActualHttpClient)
container.RegisterSingletonDecorator[HttpClient, LoggingHttpClientDecorator](); # mimics the SimpleInjector syntax

With this code, resolving HttpClient would return LoggingHttpClientDecorator decorating ActualHttpClient.
SimpleInjector also supports collection injections, e.g. injecting something like Iterable[EventHandler], and apply a decorator to all of the EventHandler instances registered to the collection.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions