typedi icon indicating copy to clipboard operation
typedi copied to clipboard

fix: non-reconstructable services are erased when imported

Open freshgum-bubbles opened this issue 2 years ago • 1 comments

Description

I found a bug in my fork of TypeDI, and I thought I'd be a good neighbour by also posting it here.

With the current inheritance code, when a value is imported from the default container, its value is always set to EMPTY_VALUE. This breaks non-reconstructable services, which lack either a type or a factory which allows for re-constructing the service.

Minimal code-snippet showcasing the problem

import 'reflect-metadata';
import { Container, ContainerInstance, Token } from 'typedi';

const myContainer = new ContainerInstance('my-container');

// Set a value on the default container:
const name = new Token<string>();

// Set it with a string value.
// This makes it non-reconstructable, as when it's imported and
// its value is erased, we have no way to reconstruct it (via, e.g.
// a factory or a constructor)
Container.set({ id: name, value: 'Joanna' });

// This breaks:
myContainer.get(name);

StackBlitz Demo

Full error:

Cannot instantiate the requested value for the "Token<UNSET_NAME>" identifier. The related metadata doesn't contain a factory or a type to instantiate.

Expected behavior

If a service can't be reconstructed from a type or a factory, it shouldn't be erased when imported from the default container.

Actual behavior

The value is always erased.

The problem is caused by this line: https://github.com/typestack/typedi/blob/072fbf9d3678dcae90264114a9fbae30d63880cf/src/container-instance.class.ts#L96

freshgum-bubbles avatar Jul 15 '23 13:07 freshgum-bubbles

I fixed this in my fork by doing the following:

https://github.com/freshgum-bubbles/typedi/blob/d69e6f45afda817378adc2a35aad9d490c418b2a/src/container-instance.class.ts#L346-L359

(gah, it won't embed)

I'd be more than happy to open a PR for this, but I'd like the go-ahead from yourselves (as this project seems to be abandoned).

~~Man, you guys work slowly :P~~

freshgum-bubbles avatar Jul 15 '23 13:07 freshgum-bubbles