Could someone explain Components?


Ok, I implemented a Component and it is working perfectly. Hell it does the job well enough that I want to publish it as an extension, but I don’t know why it works though. Yes, I understand dependency injection as a pattern, but I generally leverage the documentation in a framework (Like werkzeug) to get into the details.

I can read in apistar.core the Component class definition, and I see that it’s iterable. Why is that necessary? What is it doing with the init function? Preload?

I think the answers I am looking for reside in apistar.components.dependency. I am just struggling to convert code in my head to something like a natural language explanation.

Any help would be appreciated. Thanks guys.


Ok, I think I am going to take my own shot at this, if anyone wants to chime in please do so.

When we instantiate an instance of an API Star App we pass an optional list of components. A Component is simply an iterable object that returns a type, a factory function for creating that type of object, and a Boolean preload value. By default preload=False which means the framework must use the provided factory function each time to provide an instance of that component type. If preload=True API Star creates a singleton object of that Component using the factory function. Preloaded components are added to the initial_state passed to the DependencyInjector

The list of Components passed to the App initializer is added to that framework’s BUILTIN_COMPONENTS and HTTP_COMPONENTS and passed to the DependencyInjector initializer. It is here that the DependencyInjector builds out the steps required to complete a function call, resolving any of the annotated parameters and providing instances of our components when required to complete the steps.