SqlConnection Singleton - singleton

Greetings, I would like to ask if creating Singleton to have only one active connection to db is a good idea. What i would like to do is:
1) I have a wcf service
2) wcf service gets data from db
3) i would like to create a singleton like this to have only one connection to db:
private static PersistanceSingleton _Instance;
public static PersistanceSingleton Instance
{
get
{
if (_Instance == null)
{
_Instance = new PersistanceSingleton();
}
return _Instance;
}
}
I know this is not an ideal singleton but i just wrote it for this post purpose.
I would like to have some persistance repositories here and which I will be instantiating them in constructor.
Inside my service class I would have the following code inside constructor
_DBPersistanceSingleton = PersistanceSingleton.Instance;
Then when some request comes (e.g. GetUsersRequest) i would like to do something like:
_DBPersistanceSingleton.GetUsers()
Before each call to db is executed I will also check whether SqlConnection is open or not.
Please let me know if this is a good practice. The reason why I think about this solution is because of large number of users that will be connecting to that service via client application

It's not a good practice to reuse SqlConnection like that. Open it when you need it and close it as soon as you're done with it. Connection pooling will work for you under the hood reusing the connection.

No, I'd strongly recommend you don't. What happens if multiple requests come in at the same time? They can't all use the same connection at the same, at best you'd just be introducing a big bottleneck.
Connection pooling is handled automatically for you, and takes the hassle away from you so you don't need to worry about it. Just open and close connections as needed.

Putting the sql connection aside...
This singleton pattern is not thread safe and is a bad idea to use in a multi-threaded application (as your WCF service is likely to be).
With this code, if multiple simultaneous requests arrive, it is possible that multiple instances will be created.

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.

Calling multiple operations on a WCF client

I am currently looking at some code which basically reads data line-by-line from a file and calls an appropriate method on a WCF client for each line. My problem with the code is that a new client is created for each operation ie:
function CallSomeOp(line)
{
using (var client = new Client()
{
client.SomeOp(line);
}
}
This seems to make the client close the connection and reopen a new one for each line in the file which seems like a big overhead. What I would like to do is move the creation of the client outside the function and into initialization, so that multiple operations are called on one client, ie:
using (var client = new Client())
{
for(var line in lines)
{
CallSomeOp(line, client);
}
}
But I'm not sure if this is OK or not. Is there some problem with calling multiple operations on a client, ie will I eventually run out of memory or something?
An operation is typically stateless, so that's expected behaviour. You can change the InstanceContextMode though. This determines if a new instance is created with each call or that there is a single instance. The question is, should you? Like I said, a single call is typically stateless. Having just a single instance doesn't scale very well either. I'd suggest to keep InstanceContextMode to be PerCall, that way, for every call the webserver creates a single instance, I wouldn't worry too much about overhead. If overhead really does become a problem, maybe a service isn't what you need.
Then there's the ConcurrencyMode which allows you to specify multiple threads to be created.
As far as the client is concerned, you don't need to re-create it everytime you want to call an operation. Alternatively, you could also look at the ChannelFactory if both client and server have knowledge of the contract. This answer provides some detail.
It's definitely a good idea to reuse a WCF client across multiple calls, since there is indeed a cost in creating new instances of it, even if that's been improved in later versions.
The most important thing to be aware of when reusing a WCF client, though, is that if a service operation fails, the whole client will be put in a faulted state and can no longer be used.
You will have to take this into consideration in your client code. Depending on your requirements, one way to handle this situation could be to recreate the client proxy in case of failure and continue processing the input, like shown in this example:
var client = new ServiceClient();
foreach (var line in lines)
{
try
{
client.DoSomething(line);
}
catch
{
client.Abort();
client = new ServiceClient()
}
}
Note that you may also want to keep track of how many times the service call fails and with what type of exception, since in some situations it would make more sense to completely abort the operation instead of keep trying, e.g. when the remote service is not reachable.

How to keep vaadin application instances from interfering with eachother?

I've got a Vaadin application and I'm getting some strange behaviour when running two instances of the application at the same time (one in FF, another in IE). I've already removed most static objects (these caused the application to completely reload when used parallel to another open application) and now I can interact normally with the UI without the complete reset. However, I'm now noticing that I'm getting only one user's data in both interfaces. I assume this is caused by singleton objects I'm using to manage some data caching and a SOAP connection. I'd like to know if it's the singleton pattern itself that's causing the strange output or is it just the static instance object I'm keeping?
I've tried using ThreadLocal with my singleton, but all my variables are always null when I try to use them in my singleton's functions. Currently my singleton contains this, which is probably terribly, terribly wrong since it doesn't work.
private static ThreadLocal<SoapClient> instance = new ThreadLocal<SoapClient>();
public static synchronized SoapClient getInstance(){
if (instance.get() == null) {
instance.set(new SoapClient());
}
return instance.get();
}
I chose a singleton object so I'd always have access to the cached data and my user's soap connection everywhere in my application instance, and the only other way I can think of for doing that is to have a static object somewhere, but the static keyword seems to be the cause of all my problems in the first place. Is there any way around this or is there something else causing it?
A better way to instantiate your thread local would be this
ThreadLocal<SoapClient> instance = new ThreadLocal<String>() {
#Override
protected String initialValue() {
return new SoapClient();
}
}
However, your problem here is web app servers "pool" and re-use threads. In Vaadin terms,not every request for an application is processed same thread - i.e. Thread1 could process requests for both App instance 1 and App Instance 2. If your SoapClient caches information appropriate to App instance 1, the UI for App 2 could end up using the SoapClient for App 1.
Assuming (from your description) that "app specific" information is cached in the SoapClient, I would suggest that you
Create and store the SoapClient on your Application object as a normal field (not static, not threadlocal)
If you need to access the application (in order to get the SoapClient), and it's tricky from where you are, use the ThreadLocal access pattern. See the second example on the link. Note that the ThreadLocal is set at the beginning of the HttpRequest, and "unset" at the end, ensuring that any subsequent requests on the same thread do NOT get the same application instance.

WCF Service Client Lifetime

I have a WPF appliction that uses WCF services to make calls to the server.
I use this property in my code to access the service
private static IProjectWcfService ProjectService
{
get
{
_projectServiceFactory = new ProjectWcfServiceFactory();
return _projectServiceFactory.Create();
}
}
The Create on the factory looks like this
public IProjectWcfService Create()
{
_serviceClient = new ProjectWcfServiceClient();
//ToDo: Need some way of saving username and password
_serviceClient.ClientCredentials.UserName.UserName = "MyUsername";
_serviceClient.ClientCredentials.UserName.Password = "MyPassword";
return _serviceClient;
}
To access the service methods I use somethingn like the following.
ProjectService.Save(dto);
Is this a good approach for what I am trying to do? I am getting an errorthat I can't track down that I think may be realted to having too many service client connections open (is this possible?) notice I never close the service client or reuse it.
What would the best practice for WCF service client's be for WPF calling?
Thanks in advance...
You're on the right track, I'd say ;-)
Basically, creating the WCF client proxy is a two-step process:
create the channel factory
from the channel factory, create the actual channel
Step #1 is quite "expensive" in terms of time and effort needed - so it's definitely a good idea to do that once and then cache the instance of ProjectWcfServiceFactory somewhere in your code.
Step #2 is actually pretty lightweight, and since a channel between a client and a service can fall into a "faulted state" when an exception happens on the server (and then needs to be re-created from scratch), caching the actual channel per se is less desirable.
So the commonly accepted best practice would be:
create the ChannelFactory<T> (in your case: ProjectWcfServiceFactory) once and cache it for as long as possible; do that heavy lifting only once
create the actual Channel (here: IProjectWcfService) as needed, before every call. That way, you don't have to worry about checking its state and recreating it as needed
UPDATE: "what about closing the channel?" asks Burt ;-) Good point!!
The acccepted best practice for this is to wrap your service call in a try....catch....finally block. The tricky part is: upon disposing of the channel, things can do wrong, too, so you could get an exception - that's why wrapping it in a using(....) block isn't sufficient.
So basically you have:
IProjectWcfService client = ChannelFactory.CreateChannel();
try
{
client.MakeYourCall();
}
catch(CommunicationException ce)
{
// do any exception handling of your own
}
finally
{
ICommunicationObject comObj = ((ICommunicationObject)client);
if(comObj.State == CommunicationState.Faulted)
{
comObj.Abort();
}
else
{
comObj.Close();
}
}
And of course, you could definitely nicely wrap this into a method or an extension method or something in order not to have to type this out every time you make a service call.
UPDATE:
The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.
Learning WCF http://ecx.images-amazon.com/images/I/41wYa%2BNiPML._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg
The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming.

NHibernate session management in Windows Service applications

I'm developing and application that runs as a Windows service. There are other components which include a few WCF services, a client GUI and so on - but it is the Windows service that access the database.
So, the application is a long-running server, and I'd like to improve its performance and scalability, I was looking to improve data access among other things. I posted in another thread about second-level caching.
This post is about session management for the long-running thread that accesses the database.
Should I be using a thread-static context?
If so, is there any example of how that would be implemented.
Every one around the net who is using NHibernate seem to be heavily focussed on web-application style architectures. There seems to be a great lack of documentation / discussion for non-web app designs.
At the moment, my long running thread does this:
Call 3 or 4 DAO methods
Verify the state of the detached objects returned.
Update the state if needed.
Call a couple of DAO methods to persist the updated instances. (pass in the id of the object and the instance itself - the DAO will retrieve the object from the DB again, and set the updated values and session.SaveOrUpdate() before committing the transaction.
Sleep for 'n' seconds
Repeat all over again!
So, the following is a common pattern we use for each of the DAO methods:
Open session using sessionFactory.OpenSession()
Begin transaction
Do db work. retrieve / update etc
Commit trans
(Rollback in case of exceptions)
Finally always dispose transaction and session.Close()
This happens for every method call to a DAO class.
I suspect this is some sort of an anti-pattern the way we are doing it.
However, I'm not able to find enough direction anywhere as to how we could improve it.
Pls note, while this thread is running in the background, doing its stuff, there are requests coming in from the WCF clients each of which could make 2-3 DAO calls themselves - sometimes querying/updating the same objects the long running thread deals with.
Any ideas / suggestions / pointers to improve our design will be greatly appreciated.
If we can get some good discussion going, we could make this a community wiki, and possbily link to here from http://nhibernate.info
Krishna
There seems to be a great lack of documentation / discussion for non-web app designs.
This has also been my experience. However, the model you are following seems correct to me. You should always open a session, commit changes, then close it again.
This question is a little old now, but another technique would be to use Contextual Sessions rather than creating a new session in each DAO.
In our case, we're thinking of creating the session once per thread (for our multi-threaded win32 service), and make it available to the DAOs using either a property that returns SessionFactory.GetCurrentSession() (using the ThreadContext current session provider, so it's session-per-thread) or via DI (dependency injection - once again using ThreadContext.)
More info on GetCurrentSession and Contextual Sessions here.
You can also flush the session without actually closing it and it achieves the same thing. I do.
We've recently started using an IoC container to manage session lifecycle, as a replacement for the contextual sessions mentioned above. (More details here).
I agree, there aren't many examples for stateful apps.
I'm thinking of doing the following:
Like you I have a windows service hosting a number of WCF services. So the WCF services are the entry points.
Ultimately all my WCF services inherit from AbstractService - which handles a lot of logging and basic DB inserts/updates.
In one of the best NHibernate posts I've seen, a HttpModule does the following:
see http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx
private void BeginTransaction(object sender, EventArgs e) {
NHibernateSessionManager.Instance.BeginTransaction();
}
private void CommitAndCloseSession(object sender, EventArgs e) {
try {
NHibernateSessionManager.Instance.CommitTransaction();
}
finally {
NHibernateSessionManager.Instance.CloseSession();
}
}
So perhaps I should do something similar in AbstractService. So effectively I'll end up with a session per service invocation. If you examine the NHib best practices article link above, you'll see that the NHibernateSessionManager should deal with everything else, as long as I open and close the session (AbstractService constructor and destructor).
Just a thought. But I'm experiencing errors because my session seems to be hanging around for too long, and I'm getting the infamous error - NHibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs).