Skip to content

Injected dependency isn't instantiated when other than toClass binding is used #11

@kirilldronkin

Description

@kirilldronkin

A minimal reproducible demo:

import React, {Fragment, FunctionComponent} from 'react';
import {render} from 'react-dom';
import {provider, inject, toClass, toFactory, useInstance} from 'react-ioc';

class ServiceB {
	bar(): string {
		return 'bar';
	}
}

class ServiceA {
	@inject serviceB: ServiceB;

	foo(): string {
		return 'foo' + this.serviceB.bar();
	}
}

const bindings = [
	[ServiceB, toClass(ServiceB)],
	[ServiceA, toFactory(() => new ServiceA())]
];

const Provider = provider(...bindings)(Fragment);

const App: FunctionComponent = () => {
	const serviceA = useInstance(ServiceA);

	return <span>{serviceA.foo()}</span>;
};

render(<Provider><App /></Provider>, document.body);

Here we expect foobar in the document body, but instead get Dependency ServiceB is not found and TypeError: Cannot read property 'bar' of undefined respectively. But if change toFactory(() => new ServiceB()) to toClass(ServiceB) (or simple ServiceB but I prefer to pass binding explicitly) everything works fine.

Looks like saving the injector to an instance is implemented only in toClass binding, is it by design? Maybe we can lift it up to asBinding utility? BTW it still work if serviceB is accessed (or injected directly) during instantiating of ServiceA by saving the injector to currentInjector variable under the hood:

class ServiceA {
	@inject serviceB: ServiceB;

	constructor() {
		this.serviceB;
	}

	foo(): string {
		return 'foo' + this.serviceB.bar();
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions