Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton injection with parameter

I do want to use the packages get_it and injectable. They are both wonderful, but I'm facing a issue. Maybe my idea is wrong.

My application has two singletons and I want to use different base urls for different app flavors. So I added a parameter to the singleton constructor with the baseUrl value.

The problem is now, that injectable has only @factoryParam as annotation. The name shows the problem. It's not for singletons.

What will be the best practice for that issue? Should I get rid of constructor injection and inject the baseUrl within the singleton like

var url = get_it.get<Config>();

or is that not the best idea?

like image 617
mars3142 Avatar asked Apr 01 '26 00:04

mars3142


1 Answers

It can be achievied in few ways, you can register different strings for different env e.g.

@Environment("dev")
@Named("url") // in case if you injecting other strings
String get devUrl...

@Environment("stage")
@Named("url") // in case if you injecting other strings
String get stageUrl...

[Update with example]

@Environment("dev")
@injectable
class ExampleOne{
final String _url;

ExampleOne(@Named("url") this._url)
}

@Environment("stage")
@injectable
class ExampleTwo{
final String _url;

ExampleTwo(@Named("url") this._url);
}

or just one class:

@injectable
class Example{
final String _url;
Example(@Named("url") this._url);
}
like image 161
Daniel Jasiński Avatar answered Apr 03 '26 15:04

Daniel Jasiński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!