How to share an instance of a singleton class between two windows - singleton

I am working with small electron application, and I want to ask one small question.
I need to share a singleton class instance between different two windows of my app.
“Share” means instance which has each class is the same and variables of the instance are the same.
I used affinity parameter in the BrowserWindow() constructor to run two windows in the same renderer process. I suppose if the two windows run in the same process, the two windows share the instance. But actually, the instance and the values of the instance are different.
Is this a correct behavior?
1.If so, could you tell me another way to share an instance between two windows?
2.If not, is this a bug? Or do I need to set another parameter?

affinity option exposes control to chromimum's process model (https://github.com/electron/electron/issues/11484 / https://www.chromium.org/developers/design-documents/process-models) and none of chromium's process model allows share hosted page's context between. Running two site in single process doesn't necessarily mean two hosted sites shares context, especially it exposes whole security concerns around.
There is no such thing for singleton in electron, at least from out of box supported way via electron's supported api surface. Though it's not true sharing, sync via ipc is nearly only way to go.

i use window.open() method to create new BrowserWindow, when use this method, you can paas your javascript singleton class by window
render-process
const modal = window.open(filePath, 'xxx');
modal.window.singletonClass = window.singletonClass;
main process
mainWindow.webContents.on('new-window', ()=> {});

Related

Facade in Object Oriented Programming

In OOP, should a Facade be an object or just a class? Which is better?
Most of the examples in Wikipedia creates Facade as an object which should be instantiated before use.
CarFacade cf = new CarFacade();
cf.start();
Can it be designed to be like this instead?
CarFacade.start();
UPDATE
Can a Facade facilitate a singleton?
A facade
represents a high level API for a complex subsystem (module).
reduces client code dependencies.
This means that your client code only uses the facade and does
not have a lot of dependencies to classes behind that facade.
It is better to use an instance of an interface, because
you can replace it for tests. E.g. mock the subsystem the facade represents.
you can replace it at runtime.
When you use a static methods, your client code is bound to that method implementations at compile-time. This is usually the opposite of the open/close principle.
I said "usually the opposite", because there are examples when static methods are used, but the system is still open for extension. E.g.
ServiceLoader
The static load methods only scan the classpath and lookup service implementations. Thus adding classes and META-INF/services descriptions to the classpath will add other available services without changing the ServiceLoader's code.
Spring's AuthenticationFacade for example uses a ThreadLocal internally. This makes it possible to replace the behavior of the AuthenticationFacade. Thus it is open for extension too.
Finally I think it is better to use an instance and interface like I would use for most of the other classes.
It's two fold. You can use it as a static method. Say for instance in spring security I use AuthenticationFacade to access currently logged in user Principal details like so. AuthenticationFacade.getName()
There are other instances, in which mostly people create an instance of Facade and use it. In my opinion neither approach is superior over the other. Rather it depends on your context.
Finally Facade can use Singleton pattern to make sure that it creates only one instance and provides a global point of access to it.
This question is highly subjective. The only reason I am responding is because I reviewed some of my own code and found where I had written a Façade in one application as a singleton and written almost the same Façade in a different application requiring an instance. I'm going to discuss why I chose each of those routes in their respective applications so that I can evaluate if I made the correct choice.
A façade vs the open/close principle is already explained by #Rene Link. In my personal experience, you have to think of it this way: Does the object hold the state of itself?
Let's say I have a façade that wraps the Azure Storage API for .NET (https://learn.microsoft.com/en-us/azure/storage/common/storage-samples-dotnet)
This facade holds information about how to authenticate against the storage API so that it the client can do something like this:
Azure.Authenticate(username, password);
Azure.CreateFile("My New Text File", "\\FILELOCATION");
As you can see in this example, I have not created an instance and i'm using static methods, therefore following the singleton pattern. While this makes for code that is more concise, I now have an issue if I need to authenticate to a given path with a different credential than the one already provided, I would have to do something like this:
Azure.Authenticate(username, password)
Azure.CreateFile("My New Text File", "\\FILELOCATION");
Azure.Authenticate(username2, password2);
Azure.CreateFile("My Restrictied Text File", "\\RESTRTICTEDFILELOCATION");
While this would work, it can be hard to determine why authentication failed when I call Azure.ReadFile, as I have no idea what username and password may have been passed into the singleton from thread4 on form2 (which is no where to found) This is a prime example of where you should be using an instance. It would make much more since to do something like this:
Using (AzureFacade myAzure = Azure.Authenticate(username, password))
{
Azure.CreateFile("My New Text File", "\\FILELOCATION"); // I will always know the username and password.
}
With that said, what happens if the developer needs to create a file in Azure in a method that has no idea what the username and password to Azure may be. A good example of this would be an application that periodically connects to Azure and performs some multi-threaded tasks. In said application, the user setups a connection string to azure and all mulit-threaded tasks are performed using that connection string. Therefore, there is no need to create an instance for each thread (as the state of the object will always be the same) However, in order to maintain thread safety, you don't want to share the same instance across all the threads. This is where a singleton, thread-safe pattern may come into play. (Spring's AuthenticationFacade according to #Rene Link) So that I could do something like this (psudocode)
Thread[] allTask = // Create 5 threads
Azure.Authenticate(username, password) // Authenticate for all 5 threads.
allTask.start(myfunction)
void myFunction()
{
Azure.CreateFile("x");
}
Therefore, the choice between an instance of a façade v. a singleton façade is completely dependent on the intended application of the facade, however both can definitely exist.

How should one write an XPC service with state?

I've read the NSXPC* docs, which advise making the vended service as stateless as possible. It's a good idea, at least to the docs and examples I've read, since the service and the calling app see each other as singletons and only one instance of the service runs at a time. This means that the methods are essentially non-member functions (to use a C++ term).
Why do I want to get around this? I want to put the network code into a XPC. Since the XPC will be working with a GUI app, which will have multiple windows, I need to support multiple simultaneous connections. That doesn't work with singletons, at least directly.
The network API is C-based, with the main state type a pointer to a custom struct. So why don't we do something similar:
Have the creation function return a value type, like NSUUID or something. (Passing a pointer across processes would be a bad idea.)
In the service, create a NSDictionary (or std::map or whatever) mapping between the NSUUID and the API C-pointer.
The various service APIs take the UUID and convert it to the C-pointer to use the network API.
Aside: Since the token is random, if the XPC service crashes, the main app will have a token that's useless after the XPC is restarted. Maybe I should a URL (which would have all the information to restart) instead. But then we get potential conflicts if two connections happen to be to the same server. Maybe I can combine the ideas with the token being a URL/UUID pair. (The UUID value would move from being returned by the service to supplied by the main app.)
Would this be a good way to implement state-full XPCs?
You may want to add a method to your service interface which replies with a long-lived proxy object. You can arrange for this to happen by means of a call to -[NSXPCInterface setInterface:forSelector:argumentIndex:ofReply:], passing YES for the last parameter. Details are available here:
https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSXPCInterface_reference/#//apple_ref/occ/instm/NSXPCInterface/setInterface:forSelector:argumentIndex:ofReply:

How to have multiple singleton instance when user regenerate the data structure in application?

I have an application which uses back ground worker(bw) and tasks.
I have one singleton instance in this app..which contains most of the common info about that instance of application. I have different agents listed in my app..and if I switch to different agent, i have to build entire data structure (models/viewmodels/DTOs)
Lets say, for agent "a" one of the bw is spawned...and it uses the above mentioned singleton instance...
Soon I switch to agent "b"...so in my app, i create new data structure for aganet "b". But uses the same singleton instance.
If I change any property in this singleton instance...there is a chance that the new value will be used by bw spawned for agent "a".
Can somebody help me to overcome this situation?
Can I have different singleton instance for different agents ?
Any help would be appreciated. Thanks
EDIT : Any different approach if you can tell me it would be great.
A singleton, by definition, can only exist once. If you want different settings for each user, you will need to use a different architecture. See http://sourcemaking.com/design_patterns/singleton for more information about singletons.

Passing client context using Unity in WCF service application

I have a WCF service application (actually, it uses WCF Web API preview 5) that intercepts each request and extracts several header values passed from the client. The idea is that the 'interceptor' will extract these values and setup a ClientContext object that is then globally available within the application for the duration of the request. The server is stateless, so the context is per-call.
My problem is that the application uses IoC (Unity) for dependency injection so there is no use of singleton's, etc. Any class that needs to use the context receives it via DI.
So, how do I 'dynamically' create a new context object for each request and make sure that it is used by the container for the duration of that request? I also need to be sure that it is completely thread-safe in that each request is truly using the correct instance.
UPDATE
So I realize as I look into the suggestions below that part of my problem is encapsulation. The idea is that the interface used for the context (IClientContext) contains only read-only properties so that the rest of the application code doesn't have the ability to make changes. (And in a team development environment, if the code allows it, someone will inevitably do it.)
As a result, in my message handler that intercepts the request, I can get an instance of the type implementing the interface from the container but I can't make use of it. I still want to only expose a read-only interface to all other code but need a way to set the property values. Any ideas?
I'm considering implementing two interfaces, one that provides read-only access and one that allows me to initialize the instance. Or casting the resolved object to a type that allows me to set the values. Unfortunately, this isn't fool-proof either but unless someone has a better idea, it might be the best I can do.
Read Andrew Oakley's Blog on WCF specific lifetime managers. He creates a UnityOperationContextLifetimeManager:
we came up with the idea to build a Unity lifetime manager tied to
WCF's OperationContext. That way, our container objects would live
only for the lifetime of the request...
Configure your context class with that lifetime manager and then just resolve it. It should give you an "operation singleton".
Sounds like you need a Unity LifetimeManager. See this SO question or this MSDN article.

WCF Named Pipe IPC

I have been trying to get up to speed on Named Pipes this week. The task I am trying to solve with them is that I have an existing windows service that is acting as a device driver that funnels data from an external device into a database. Now I have to modify this service and add an optional user front end (on the same machine, using a form of IPC) that can monitor the data as it passes between the device and the DB as well as send some commands back to the service.
My initial ideas for the IPC were either named pipes or memory mapped files. So far I have been working through the named pipe idea using WCF Tutorial Basic Interprocess Communication . My idea is to set the Windows service up with an additional thread that implements the WCF NamedPipe Service and use that as a conduit to the internals of my driver.
I have the sample code working, however I can not get my head around 2 issues that I am hoping that someone here can help me with:
In the tutorial the ServiceHost is instantiated with a typeof(StringReverser) rather than by referencing a concrete class. Thus there seems to be no mechanism for the Server to interact with the service itself (between the host.Open() and host.Close() lines). Is it possible to create a link between and pass information between the server and the class that actually implements the service? If so, how?
If I run a single instance of the server and then run multiple instance of the clients, it seems that each client gets a separate instance of the service class. I tried adding some state information to the class implementing the service and it was only retained within the instance of the named pipe. This is possibly related to the first question, but is there anyway to force the named pipes to use the same instance of the class that is implementing the service?
Finally, any thoughts on MMF vs Named Pipes?
Edit - About the solution
As per Tomasr's answer the solution lies in using the correct constructor in order to supply a concrete singleton class that implements the service (ServiceHost Constructor (Object, Uri[])). What I did not appreciate at the time was his reference to ensuring the service class was thread safe. Naively just changing the constructor caused a crash in the server, and that ultimately lead me down the path of understanding InstanceContextMode from this blog entry Instancecontextmode And Concurrencymode. Setting the correct context nicely finished off the solution.
For (1) and (2) the answer is simple: You can ask WCF to use a singleton instance of your service to handle all requests. Mostly all you need to do is use the alternate ServiceHost constructor that takes an Object instance instead of a type.
Notice, however, that you'll be responsible for making your service class thread safe.
As for 3, it really depends a lot on what you need to do, your performance needs, how many clients you expect at the same time, the amount of data you'll be moving and for how long it needs to be available, etc.