python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Question: How to build parameterized singleton

Open Matthias-Thul opened this issue 3 years ago • 1 comments

Hi,

consider the following class:

@dataclass
class X:
    a: int
    b: int

My aim is to have b injected and have a single instance of X for each value of a. With a factory provider, I can do the following:

class Container(DeclarativeContainer):
    x_factory = Factory(X, b=42)


if __name__ == '__main__':
    container = Container()
    x = container.x_factory(1)
    print(id(x), x)
    x_2 = container.x_factory(2)
    print(id(x_2), x_2)
    x_3 = container.x_factory(2)
    print(id(x_3), x_3)

This constructs three instances of X (two with a=2) as expected. However, I want to have the above return only two instances of X, one with a=1 and one with a=2. I tried:

class Container(DeclarativeContainer):
    x_factory = Singleton(X, b=42)

This returned a single instance however, independent of the value of a that I pass to the x_factory.

How can I achieve the desired behavior?

Thanks!

Matthias-Thul avatar Dec 20 '21 12:12 Matthias-Thul

It does not really seem like a factory pattern to me when you put it that way. I think you want some combination of SelectorProvider and ConfigProvider. Try re-framing what you want to accomplish.

rowan-maclachlan avatar Apr 26 '22 00:04 rowan-maclachlan