Search code examples
angulardependency-injectionangular7

How to clear the provider cache to use with useFactory in Angular 7


I am creating elements on the fly and one of these elements is using an @Inject token that resolves to a factory.

The problem is that the factory instance is cached on a node index. Once my element disappear from the view, and comes back, I expect to get a call to my factory function; but I do not. Instead I get a cached version of this factory instance.

enter image description here

How to ensure that the cache is not used after the object has disappeared from the view?

Basically, when my @Component constructor is called, I expect a brand new service. Not a cached service.

@Inject(FORM_GROUP_MANAGER_SERVICE)
private formGroupManagerService: FormGroupManagerServiceImpl
{
    provide: FORM_GROUP_MANAGER_SERVICE,
    useFactory: (structureControlService, createTonicControlFactory, parent) => new FormGroupManagerService(
        structureControlService,
        createTonicControlFactory,
        parent
    ),
    deps: [StructureControlService, FORM_GROUP_MANAGER_SERVICE_CREATE_CONTROL, [new Optional(), FormGroupManagerService]]
},

Solution

  • There is indeed a feature request for this in the angular repo, but for now I can think of 2 approaches:

    • Directly inject the factory method instead of the resolved instance of it. This way a client of it could resolve instances by itself, making it responsable for the lifetime of the resolved object as well.

    • Register the factory provider at directive/component level as in this blitz