Decoupling the dependency injection framework


#1

Hi all,

We want to use the dependency injection framework decoupled from the web stuff. It was very easy thanks to the great design of APIStar.

There is something to be aware?

from apistar.server.components import Component
from apistar.server.injector import Injector


def t1(a_int: int, a_str: str):
    return f't1: {type(a_int)}:{repr(a_int)} {type(a_str)}:{repr(a_str)}'


def t2(a_int: int):
    return f't2: {type(a_int)}:{repr(a_int)}'


class IntComponent(Component):

    def resolve(self, stream: bytes) -> int:
        return int(stream.decode())


class StrComponent(Component):

    def resolve(self, stream: bytes) -> str:
        return str(stream.decode())


injector = Injector(
    [IntComponent(), StrComponent()],
    {'stream': bytes}
)

r1 = injector.run([t1], {'stream': b'1'})
r2 = injector.run([t2], {'stream': b'2'})

print(r1)
print(r2)

The output was:

t1: <class 'int'>:1 <class 'str'>:'1'
t2: <class 'int'>:2

#2

Cool - really pleased to see folks starting to take a look at the upcoming 0.4.

I wasn’t quiet sure if you’re asking a question here or not - the output looks as you’d expect, right?

And yes, it’s perfectly reasonable to use the Dependency Injection, but none of the rest of the framework. We might try to keep the install dependencies to a minimum in order to cater to that type of use-case.

It is possible that there’ll be a few tweaks to the API before this lands…

  1. Perhaps forcing a more explicit style of can_handle_parameter methods on components, rather than just relying on the type of return annotation.
  2. Perhaps changing the API for initial data slightly.

#3

Was just about it what I wanted. Nice!

I guess that hardly can_handle_parameter could be more explicit as the parameter name and annotation is all that we have to know which dependencies to inject. What do you propose?

You could also separate the dependency injection into another library. Or to have conditional features: if it has Werkzeug, than provide App and REST stuff; if it has Jinja, than it render HTML; if it has Whitenoise than serve static resources, and so on.