Fundamentals - Dependency Injection III

How Aurelia Uses Containers:

- All view-models, components, services etc are created with DI. Aurelia makes heavy use of child containers. There are basically three cases where child containers get created & used by Aurelia.

Custom Elements & Custom Attributes

- When Aurelia creates a View, that view may contain occurrences of custom elements & custom attributes. 
- Any time an HTML element is found to either be a custom element or have custom attributes, Aurelia creates a child container for that element, parented to the closest custom element container(or the view itself). Aurelia does not create child containers when there are plain HTML elements or elements with only binding expressions, value converters etc  
- It then manually registers the elements/attributes in the child container as singletons
- This ensures that the elements & attributes aren't singletons at the application level or even the view level, which would not make sense. Instead, they are scoped to their location in the DOM. As a result of this, the HTML behaviors have access to classes registered above them in the DOM & on the same element. Likewise, they can be injected into classes that are created through their child element containers

Routed Components:

Each time the Router navigates to a screen, it creates a child container to encapsulate all the resources related to that navigation event & then auto-registers the screen's view-model in that child container.

Dynamic Components:

Dynamic composition, whether through the <compose> element or through the CompositionEngine also creates child containers with auto-registration behavior, just like the Router. In fact, the RouteLoader simply calls the CompositionEngine internally to do the heavy lifting.

The General Rule for Aurelia's DI use:

Everything is an application-level singleton except for those things which are classified as "components", essentially custom elements, custom attributes & view-models created through the router or composition engine. You can change the lifetime of router & composition created components through explicit configuration.

Comments

Popular posts from this blog

Fundamentals - App Config & Startup - VIII

Fundamentals - Dependency Injection V

Style vs Css attribute