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

[Question] Is there a way to pass parameters to a concrete type when registering? #44

Open
amura11 opened this issue Apr 29, 2021 · 3 comments
Labels
question Further information is requested

Comments

@amura11
Copy link

amura11 commented Apr 29, 2021

Assuming I have the following:

interface IMyService {
	doTheThing(): void;
}

class MyService extends IMyService {
	 constructor(baseUrl: string) {
		this.baseUrl = baseUrl;
	}
	
	doTheThing(): void {
		//Do something here
	}
	
	private baseUrl!: string;
}

Is there a way to pass baseUrl when registering MyService with the container? Something like: container.addTransient<IMyService>(() => new MyService("BaseUrl"));? Coming from C# this is typically how it's done so I might just be approaching this completely wrong.

I want to set baseUrl at the time of registering as it will change depending on the environment.

@CKGrafico CKGrafico added the question Further information is requested label Apr 29, 2021
@CKGrafico
Copy link
Owner

Hello and thanks for your question, if you want to pass the same baseUrl to all the instances of your service I think the good practise (in inversify) is to use a Factory https://github.com/inversify/InversifyJS/blob/master/wiki/factory_injection.md

If you want to have different baseUrl for each instance I usually create another method instead of passing to the constructor.

Please confirm, that this helped you and have a nice day.

@amura11
Copy link
Author

amura11 commented May 6, 2021

Would it be possible to extend the container with something like:

class CustomContainer extends Container {
    public addDynamicTransient<T>(constructor: Constructor<T>, func: () => T): interfaces.BindingWhenOnSyntax<T> {
        const id = generateIdAndAddToCache(constructor);
        this.decorateCatchable(injectable(), constructor);

        return super.bind<T>(id).toDynamicValue(func).inTransientScope();
    }
}

const container = new CustomContainer();

container.addDynamicTransient<IMyService>(MyService, () => new MyService("BaseUrl"));

I tried exactly this but I get an error that no bindings were found

@CKGrafico
Copy link
Owner

Why are you extending the container and not using as factory?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants