I have used the singleton pattern to create a single instance of a web service that I use in my win forms application. I have seen that this is good practice for web applications. I was wondering if this is the same for winform apps too? Also, should I worry about disposing of the web service (i.e. the proxy object afterwards) – it has a .Dispose method but I am not calling it anywhere in my code. In my application I am calling all my web methods asynchronously. This might sounds silly but I don’t know where I need to call dispose. Can anyone help?
class ListService
{
private static RetrieveList s_proxy;
private static readonly object s_lock = new object();
private static readonly string s_webServiceURL = Authentication.RetrieveListUrl;
internal static RetrieveList Proxy
{
get
{
lock (s_lock)
{
if (s_proxy == null)
{
s_proxy = new RetrieveList();
s_proxy.Url = s_webServiceURL;
}
return s_proxy;
}
}
}
}
If you have a single instance for an application, the object will be destroyed when the application closes or crashes. You could call Dispose in the finalizer, but that’s not guaranteed to succeed.
Unless Dispose does something vital like saving your document (it shouldn’t), I’d say, don’t worry too much. The fact it is a singleton means it lives forever and disposing is only meant to free resources that would otherwise remain around. The object remains around, so nothing to free.
However, some people may frown on this and say “what if the Dispose does something that is important to me, other than freeing resources?”. You can still call Dispose after your application has run:
As a rule of thumb, when your application as a whole needs only one instance of something, a (thread safe) singleton is often a good idea: a cache, connection to a database, a proxy, the application itself, a logger. There’s nothing that says that singletons shouldn’t apply to your WinForm apps also.
Remember however that you must carefully think about your design. What if you have a logger and the file becomes inaccessible? What if a proxy looses connection? etc, etc.