Issue setting up Singleton
In my project, I have a Singleton which I want to use in certain files. When I try to implement it in one I get an error. First, let me show some code:
The singleton:
13 Replies
Startup:
FileReader:
When i try to run this;
at line:
fileReader = new FileReader.FileReader(ServiceProvider.GetService<ISingleton>());
The thing is, is that a singleton normally wont need a public ctor.and services are registered for all parameters of a public constructorit needs a public constructor, if it has no constructor at all it implicitly has a public constructor added by the compiler
Yeah i added that one and that works. It still feels like I break something. By not having that private constructor. (I would also think that the getInstance is not needed anymore)
well if u really want to force the private constructor u would have to register the singleton using a factory method:
services.AddSingleton<ISingleton, RegularPuzzleSingleton>(serviceProvider => RegularPuzzleSingleton.GetInstance());
Okay, but wont the AddSingleton do the Singleton part for me already?
yep
usually its bad practice to design a class so that it is enforced to be a singleton
let the consumer of the class decide how many instances they want ;p
😩
I currently live in a design pattern hell.
We need to make a sudoku game with building design patterns
I basically wanted a singleton so i can create the class above just once and use it everywere (only 2 places)
registering the class as singleton in the DI container is totally fine. u simply decided then that u only need that one "global" instance
but because u enforce it via private constructor + static getter method, u are forced to and couldnt for example use an instance per scope
So, leaving the private ctor and getInstance out it is fine?
yeah i would get rid of the private constructor and GetInstance
and keep registering it as
services.AddSingleton<ISingleton, RegularPuzzleSingleton>();
Thank you so much!!
glad i could help 😄
i would also not call the interface
ISingleton
, give it a name that describes what that service isTrue, I just named that for now and when I discussed it with my duo we gonna refactor it.