Register in root container with autoinject

I need to register a class in the root container in order to be available throughout the application. Although I want the registered class to be a subclass of its key.
What I do is:

in main.ts :

aurelia.container.registerInstance(ProductActionManager, new MyProductActionManager());

Note that I’m not registering a ‘ProductActionManager’ but a ‘MyProductActionManager’

The problem is that, in my component, the injected component is an instance of ‘ProductActionManager’ instead of ‘MyProductActionManager’. Although, if I use the root container, I correctly get an instance of ‘MyProductActionManager’.

@autoinject()
export class Index { …
constructor(private am1: ProductActionManager) {
//this.am1 is an instance of ProductActionManager
let am2 = Container.instance.get(ProductActionManager)
//am2 is an instance of MyProductActionManager
} …

My understanding was that the container didn’t care about the key but apparently, the child container cannot find the instance stored in the root container so it creates a new one.

My reason for this is that I want the default ‘ProductActionManager’ in most case except if specified by someone else. My ideal case would have been to declare an interface as a key but those are compiled away by the typescript compiler so I reverted to use a base class.

Do you know how I could achieve this?

2 Likes

Okay, by stepping through the execution, I noticed the container found a transient resolver based on the base object even though I didn’t register it. That’s because I had left a @transient decorator on the class.
When I removed the @transient decorator, everything worked as expected.

I suppose this happens because the container checks first for an element in itself, than looks for injection strategy on the class given as argument and finally in the parent.

Do you think there is a way to combine the @transient decorator on the base class (for the case when I don’t want to register the instance manually) and the root container registerTransient (for the case when I want to register a derived class)?

1 Like