-
-
Notifications
You must be signed in to change notification settings - Fork 153
How to register multiple interfaces with only 1 singleton instance #157
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
Comments
Yep, that's absolutely ok |
@escamoteur Thanks. Hope you’re having a great day 😊 |
Maybe it’s trivial for some, but I just wanted to point out that as per the code example provided above, unless the DatabaseImpl class is truly implemented following the Singleton Pattern (this has nothing to do with GetIt), the code above would be generating 2 instances of the DatabaseImpl class, not one like it could be expected (as per the what the GetIt singleton method name suggests..), since the DatabaseImpl() constructor will effectively be called twice. |
No, it does what it says. It registers two Singletons that share the same code. you will always get the correct instance when querying with getit for the interface type. |
@escamoteur correct, but let me put this in a other way then: how would you go with mapping 2 different interfaces for the same one unique singleton instance of an implementing class? (that’s actually my current use case/requirement, to be able to call getIt from different locations in my code, and calling it with different interfaces to limit the number of methods accessible to match the context of where getIt is being called, but in the end, obtain always the same unique singleton instead of different/multiple instances of the same impl class..) The only way I can think of right now, is to do like I suggested in my previous comment, which means, same getIt registration code as per the very first comment above, but making sure that the DatabaseImpl implementing class (..of the various interfaces) is internally defined as a singleton. This way, it doesn’t matter how many times its constructor DatabaseImpl() is called when doing those multiple getIt registration calls for each interface to be mapped, it will always return the same single instance (the singleton). GetIt will end up with different/multiple interfaces mapped to the same unique singleton instance, and not multiple instances of the same code like you mentioned (..which is another possibility, yes, when DatabaseImpl is not defined as a singleton, but I’m referring here to a singleton use case so it’s different). Do you see any issue with that approach, or any better way to implement this many-interfaces-to-one-impl-instance with getIt? |
For example, I want to register multiple interfaces:
DatabaseReadable
,DatabaseWritable
with only 1 singleton ofDatabaseImpl
. Does the code below work?The text was updated successfully, but these errors were encountered: