Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kirilldronkin opened this issue Feb 20, 2020 · 0 comments

Comments

@kirilldronkin
Copy link

kirilldronkin commented Feb 20, 2020

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();
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant