8,748 questions
0
votes
3
answers
237
views
Singleton using Lazy<T> vs Singleton using static field initializer [duplicate]
I am storing some settings for my application in a JSON file located alongside the application .exe. I want to load these settings only once, lazily, the first time one of them is needed. So for ...
Best practices
2
votes
4
replies
127
views
When is it OK to use a singleton?
Follow-up on this question: Singletons: good design or a crutch?
It is true, that using singletons can make testing harder, and bugs can hide behind them. GoF defines singleton to use when:
Global ...
1
vote
0
answers
120
views
What makes QGuiApplication construction hang in this case?
Here's a piece of Qt code:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QGuiApplication app2(argc, argv);
The first constructor call returns, the second does not.
I ...
3
votes
1
answer
90
views
Cannot instantiate singleton class implemented by metaclass with default value
I want to instantiate class with default value.
Class have required parameters.
Class must be singleton (can be implemented with smt other than metaclass).
Data must be updated if try to instantiate ...
0
votes
0
answers
91
views
Use singleton HttpClient in .NET Core for multiple API endpoints calls
According to
[1]: https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines, the recommended approach for handling HTTP requests is to use singleton or static ...
-1
votes
0
answers
46
views
Singleton pattern in Rust [duplicate]
Goal
Implement a Singleton Design Pattern for a struct, without multiprocessing considerations.
Minimal example
Here is the base of the code, without the singleton logic.
struct ...
1
vote
2
answers
154
views
How do I test a Singleton for thread-safety in a unit test?
Everyone knows Singletons. Here is one:
public class MySingleton
{
private MySingleton() { }
public static MySingleton GetInstance()
{
return instance ??= new MySingleton();
}
...
0
votes
0
answers
53
views
why does preferencesDataStore() return the same instance? (why a class is a singleton? no need for dagger-hilt?)
This is a Kotlin question, although it originated from Android Jetpack Compose.
I defined the Context.dataStore extension property in the recommended way:
val Context.dataStore: DataStore<...
1
vote
1
answer
77
views
Correct way of resetting a singleton instance in TypeScript
I have a tracker which I'd like to be a singleton class for usage throughout the app. For instance, I came up with the following:
export class MyTracker = {
private static instance: MyTracker | ...
0
votes
0
answers
50
views
Messy call graphs for singleton classes
I'm trying to browse the C++ code for an embedded project using Doxygen 1.8.13.
I find the call/caller graphs very useful for this, but the project includes several singleton classes. Each of these ...
2
votes
3
answers
220
views
How much overhead does access of singleton have?
Does the singleton pattern in C++ have processor overhead? If it does, how much?
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
//...
int ...
2
votes
2
answers
83
views
Forbid multiple service implementations in .NET Generic Host service collection
For .NET Generic Host it is possible to register multiple implementations of same service interface. When materializing that service the last added is obtained (that is correct even for multiple ...
0
votes
2
answers
128
views
Access Services in Class to be used as Singleton
I have a class AppData that I am going to load as Singleton to store data for use across my Blazor web app.
My issue is that the singleton requires some data that is retrieved with asynchronous calls ...
0
votes
1
answer
95
views
Perform an action when all registered services in .NET Generic Host are disposed
I need to perform some action (i. e., log succesfull shutdown) when all registered services in .NET Generic Host are disposed. I hoped IHostApplicationLifetime.ApplicationStopped could help me but it ...
0
votes
1
answer
193
views
Creating a static singleton with an async initializer in rust [duplicate]
I'm working with SurrealDb, and in their docs here they implement a singleton. However, when you try to implement the same thing using a RocksDb instance it requires an asynchronous step making that ...
2
votes
1
answer
122
views
Singleton Dependencies in Background Task Channel / Hosted Background Service
I am working on creating some ASP.NET Core 8.0 Web API endpoints (in C#). There will be over 100 endpoints across 40-50 repositories that are all a part of the same platform ecosystem; it is not an ...
0
votes
1
answer
162
views
.NET Generic Host doesn't dispose all registered service instances on host shutdown
I have a .NET 8.0 console application which uses .NET generic host (Microsoft.Extensions.Hosting v8.0.0 nuget package).
I've injected a sample service which implements IDisposable. When I close my ...
-1
votes
1
answer
101
views
How to handle static variable sharing in dynamic linking of libraries?
I have a requirement in which I have to use a singleton class, acting as a database to store some values. I have also declared a run function in the cpp file of this singleton class in order to change ...
0
votes
1
answer
189
views
Using Singleton Logger class in Nestjs
I have a web application on Nest.js where I make use of pino to log exceptions .
Service1.ts
import {Logger} from 'nestjs-pino';
export class Service1{
constructor(private readonly logger : Logger) {}...
0
votes
2
answers
46
views
Python subclass constructor calls metaclass with *args and **kwargs
I am trying to instantiate a singleton with constructor argument. However, passing the input arguments to the metaclass hits an error.
from typing_extensions import List, TypedDict, Optional, Any
...
4
votes
3
answers
144
views
Reference counted singleton
I have have found the following code in my company's codebase. The logic behind is to free the config singleton when nobody is using it, as some users have been found to inflate its size, which has ...
0
votes
1
answer
65
views
Error in F# 9.0 on singleton pattern: The static initialization of a file or type resulted in static data being accessed recursively
In F# FSharp.Core(8.0.400) and Windows .NetCore 3.1, the following singleton pattern worked flawlessly:
[<AutoOpen>]
module AppointmentEventManager
open Stargate.XI.Client.Domain.Models
type ...
0
votes
0
answers
44
views
Why does the UnityPlayer become null when switching Activity in Android?
I initialized the UnityPlayer using a singleton pattern. However, when I switch activities, the UnityPlayer becomes null.
Here’s what I did:
Initialization in MainActivity:
UnityPlayerManager....
0
votes
2
answers
115
views
Singleton for UIViewControler in Swift disallowed by compiler?
I have a UIViewController class with a variable shared that allows other classes to reach it as a singleton. However, the compiler (with Main Thread Checker enabled in Scheme Settings) is flagging the ...
0
votes
1
answer
84
views
How can I retrieve data from a Scoped Service in a Singleton Service?
We've been facing an issue in our Blazor Server App
User Logs in.
When user is Authenticated is shown a companies list.
User can choose between one of the companies in the list.
In this moment we ...
1
vote
2
answers
175
views
setting thread safe dictionary of runtime vars using contextvars
Basic process explanation:
A process has some initialization parameters that have to be set dynamically at runtime. For example data for a certain amount of dates (final_lookback) have to be pulled ...
1
vote
1
answer
56
views
TypeScript: Get field value using generic method from non generic class without cast
I have a non generic singleton class (eg service). It has a set of fields whose type is a descendant of a generic type. I want to implement a generic method on that class which has a key parameter ...
0
votes
0
answers
41
views
WebSocket Connection Causes Delay on App Revisit in React Native
Problem Description:
I am using a singleton SocketConnect class to manage WebSocket connections in my React Native application. The connection works fine initially, but when I leave the app and return ...
2
votes
0
answers
550
views
Angular 19 - Why is a new @Injectable service created each time
I created a service for authentication which keeps an _isAuthenticated state as a class property. The service is marked as @injectable. I then injected the service into a route guard component.
The ...
-2
votes
1
answer
65
views
Why does the singleton class in iOS, when combined with multiple dynamic frameworks, result in multiple instances?
The main project ModuleDemo depends on ModuleA, ModuleB, and ModuleC. The description of the entire project's Podfile is roughly as follows:
platform :ios, '13.0'
use_frameworks! :linkage => :...
0
votes
0
answers
27
views
How should I go about optimizing my State handler in order to avoid bloat?
I am a game programming student early on I learned about the difference between pausing games with Time.timeScale and a singleton state machine. I really liked learning how to use a singleton and ...
0
votes
0
answers
103
views
.net core scoped service problem in repository [duplicate]
I have a .net core 8 site where i have a number of services and repositories.
This is setup by using dependency injection.
I now have created a Background service that will use som of the service and ...
2
votes
0
answers
156
views
NSCache singleton - concurrency safe (Swift 6)
I would like to make sure I understand this correctly. I created a singleton class managing cache of NumberFormatters and compiler complains about shared property not being concurrency-safe. Reasons ...
0
votes
0
answers
167
views
How to use singleton SwiftData models
I am working on a project including SwiftData, and have the following 2 models (please note only relevant parts are shown):
Chip
(like an electronics chip)
import SwiftUI
import SwiftData
@Model
class ...
0
votes
1
answer
38
views
Python Singleton - Avoid "None" reference
I have created a class that I"m attempting to implement a Singleton pattern on. When __new__ for the class is fired off, I check to see if a class-wide list of instances has a length > 0 or ...
2
votes
0
answers
61
views
Python Singleton Class with inherited __init__ not working
I am currently trying to learn a new method of programming. I am creating a Singleton class to help manage my config file, which is used across multiple areas of my code. The code that I'm using is ...
-2
votes
2
answers
100
views
Correct singleton pattern implementation? [duplicate]
I have the following singleton implementation based on a video https://youtu.be/Q6HJpgdkAK8?si=k-9ksjHirLHq5Ne2 Some features of my own implementation are different, but i want to know whether my ...
3
votes
1
answer
37
views
Singleton different behavior when using class and dict to store the instance
Why do these two base classes result in the child objects having different behavior?
class Base:
_instance: "Base" = None
def __new__(cls) -> "Base":
if cls....
1
vote
0
answers
48
views
Implementation of sinleton class, private constructor, still initiallizing, do I need to access Singleton from another class to make it work? [duplicate]
how am I able to create an instance of Singleton s3 even when the constructor is private, tried in local env and online compiler as well, it is running
public class Singleton {
// Step 1: ...
0
votes
1
answer
158
views
define_singleton_method with a block argument (or, how to give two blocks as arguments)
I'm trying to run this code, to overwrite each for an Array instance:
my_array.define_singleton_method(:each, &block) do
super { |x| x.instance_exec(&block) }
end
The problem is I get this ...
-3
votes
1
answer
94
views
I have a question about using some shared resources as static variables [closed]
I'm a student who is studying game engine structure.
I've been managing shared resources through the Singleton Patterns Manager class while creating game engines. However, as the code got longer, the ...
0
votes
1
answer
41
views
NullPointerException when I invoke method from @Schedule of @Startup @Singleton bean
When I try to invoke method of @ViewScoped Bean from @Startup @Singleton bean I always have an error NullPointerException. I use @Schedule annotation method to call @ViewScoped bean method, why it ...
2
votes
1
answer
126
views
How to implement singleton object in C?
I have a requirement for an OBJECT to be used by other objects. The requirement is that the OBJECT not require initialization by any external call. So I began with something like so...
// .h
struct ...
0
votes
1
answer
69
views
Python singleton implementation not working
I am trying to implement a singleton pattern for a config class. I have a _Config class which loads the config.yaml file. Config class is a subclass of _Config class, whenever creating an instance of ...
0
votes
1
answer
108
views
Singleton class with std map of unique_ptr is throwing error on compilation
The following code is failing to compile and i am not able to figure out why!
/* --------------------------------------------------------------- */
/* Includes */
#include <iostream>
#include &...
0
votes
1
answer
43
views
How to create a special singleton instance of a class in TypeScript or JavaScript
How to create a special singleton instance of a class in TypeScript (or JavaScript) that is not ever returned by the constructor, and yet can be referenced as any other instance of the class?
0
votes
1
answer
61
views
Is it possible to have python workers use different global context?
We have a singleton object we use for our program that refers to an ugly god-object that I wish would die - we inherited the code from a team that had already implemented it this way. Unfortunately ...
0
votes
1
answer
275
views
How to re-use a single SwiftUI view as single instance in multiple screens?
In iOS SwiftUI instantiating a single SwiftUI view is pretty easy.
How about making this single SwiftUI view instance and its rendered content available to other screens in order to display the same ...
1
vote
1
answer
551
views
Unity - Why is my Singleton throwing a NullReferenceException when I re-load the scene?
I am facing an issue with a NullReferenceException in my code. I've created a LevelManager script to manage the different scenes of my game. Inside this file ScoreKeeper object is called. This ...
0
votes
1
answer
190
views
Jest mock of a singleton function
I have a singleton class created in a module consumed within a class of an app, I am attempting to change the mock implementations return value of the singletons contained function, in the example ...