Singleton instance using a Mutex - singleton

I want to have a singleton class that can be shared across processes. So I naturally used the Mutex in .NET 4.0.
Now I have two instances of the same application running. One modifies the "Name" property of this Singleton and all I want is the other application to pick up this change. But even after the first instance releases the Mutex, the second instance is not able to succeed in the WaitOne call. I wonder why and what I am doing wrong in the code below? Please note that the entry point is the method RunSingletonAcrossProcesses().
Here's my Singleton Class
public class SingletonAcrossProcesses
{
private static SingletonAcrossProcesses _instance;
private static Mutex _mutex = new Mutex(true, #"Global\" + "sivablogz.wordpress.com SingletonMutexDemo");
protected SingletonAcrossProcesses()
{
}
public static SingletonAcrossProcesses GetInstance()
{
if (_mutex.WaitOne(TimeSpan.Zero, true))
{
if (_instance == null)
{
_instance = new SingletonAcrossProcesses();
}
_mutex.ReleaseMutex();
}
return _instance;
}
public string Name { get; set; }
public static void RunSingletonAcrossProcesses()
{
Console.WriteLine("Press any key to Instantiate the singleton...");
Console.ReadLine();
SingletonAcrossProcesses instance = SingletonAcrossProcesses.GetInstance();
if (instance != null)
{
if (String.IsNullOrEmpty(instance.Name))
{
Console.WriteLine("Enter a name for the instance...");
instance.Name = Console.ReadLine();
}
Console.WriteLine("The Instance name is: " + instance.Name);
}
else
Console.WriteLine("The Singleton Instance could not be obtained.");
Console.WriteLine("Press any key to terminate...");
Console.ReadLine();
}
}
Thanks in advance,
Siva

You appear to be running into this:
If name is not null and initiallyOwned is true, the calling thread owns the mutex only if the named system mutex was created as a result of this call. Since there is no mechanism for determining whether the named system mutex was created, it is better to specify false for initiallyOwned when calling this constructor overload. You can use the Mutex(Boolean, String, Boolean) constructor if you need to determine initial ownership.
See here: http://msdn.microsoft.com/en-us/library/f55ddskf.aspx

Related

Connection String retrieved from one DB to be used in a Class Library to access a 2nd DB...Suggestions?

Environment:
.Net, SQL Server, WinForms Desktop
Control Database (db1)
Customer Databases (db2, db3, db4, etc.)
Background:
Each of our customers requires their own database. It's a contractual obligation due to compliance with standards in certain industries. Certain users of our application only have access to specific databases.
Scenario:
The application user's username gets passed into our control database (db1) from the app on load. There's a lookup in there that determines what customer this user has access to and returns connection string info for connecting to the database of the determined customer (db2 or db3 or db4 or etc.) to be used for the life of the runtime. All of my business logic is in a DAL, as it should be, in a .Net class library.
Suggestions on the best way/ways to get the connection string information into the DAL WITHOUT passing into every constructor/method that is called on the DAL.
I came up with one possible solution, but want to pick your brains to see if there's another or better way.
Possible Solutions:
A Global module in the DAL that has public fields like "dbServer" and "dbName".
Set those and then use the DAL as needed. They would need to be set each time the DAL is used throughout the application, but at least I don't have to make the signature of every single constructor and method require connection string information.
A settings file (preferably XML) that the app writes to after getting the connection info and the DAL reads from for the life of the runtime.
Thoughts and/or suggestions? Thanks in advance.
A set up like this might help. If you are going the IoC way, then you can remove the parameterized constructor and make Connection object a dependency too. However, you will need to feed your dependency injection provider in code since connection string comes from database.
public class User
{
public string ConnectionString
{
get; set;
}
}
public class SomeBusinessEntity
{
}
public class CallerClass
{
public IBaseDataAccess<SomeBusinessEntity> DataAccess
{
get;
set;
}
public void DoSomethingWithDatabase(User user)// Or any other way to access current user
{
// Either have specific data access initialized
SpecificDataAccess<SomeBusinessEntity> specificDataAccess = new SpecificDataAccess<SomeBusinessEntity>(user.ConnectionString);
// continue
// have dependency injection here as well. Your IoC configuration must ensure that it does not kick in until we get user object
DataAccess.SomeMethod();
}
}
public interface IBaseDataAccess<T>
{
IDbConnection Connection
{
get;
}
void SomeMethod();
// Other common stuff
}
public abstract class BaseDataAccess<T> : IBaseDataAccess<T>
{
private string _connectionString;
public BaseDataAccess(string connectionString)
{
_connectionString = connectionString;
}
public virtual IDbConnection Connection
{
get
{
return new SqlConnection(_connectionString);
}
}
public abstract void SomeMethod();
// Other common stuff
}
public class SpecificDataAccess<T> : BaseDataAccess<T>
{
public SpecificDataAccess(string connectionString) : base(connectionString)
{
}
public override void SomeMethod()
{
throw new NotImplementedException();
}
public void SomeSpecificMethod()
{
using (Connection)
{
// Do something here
}
}
}
Create a ConnectionStringProvider class that will provide you the connection string
public class ConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider
// uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Using ConnectionStringProvider in your DAL
public class MyCustomerDAL
{
private ConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
_connectionStringProvider = new ConnectionStringProvider();
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
Setting/changing the connection string
new ConnectionStringProvider()
.SetCustomerConnectionString(connString);
Note
The reason i chose to use method instead of a get/set property in ConnectionStringProvider is because maybe in the future you decide to read/write these from a file, and while you could read/write from file in a property it's misleading to your consumer who thinks that a property will be a simple performance-less hit.
Using a function tells your consumer there might be some performance hit here, so use it wisely.
A little abstration for unit testing
Here is a slight variation that will enable you to abstract for unit testing (and eventually IoC)
public class MyCustomerDAL
{
private IConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
//since not using IoC, here you have to explicitly new it up
_connectionStringProvider = new ConnectionStringProvider();
}
//i know you don't want constructor, i included this to demonstrate how you'd override for writing tests
public MyCustomerDAL(IConnectionStringProvider connectionStringProvider)
{
_connectionStringProvider = connectionStringProvider;
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
// this interface lives either in a separate abstraction/contracts library
// or it could live inside of you DAL library
public interface IConnectionStringProvider
{
string GetCustomerConnectionString();
void SetCustomerConnectionString(string connectionString);
}
public class ConnectionStringProvider : IConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Appendix A - Using IoC and DI
Disclaimer: the goal of this next piece about IoC is not to say one way is right or wrong, it's merely to bring up the idea as another way to approach solving the problem.
For this particular situation Dependency Injection would make your solving the problem super simple; specifically if you were using an IoC container combined with constructor injection.
I don't mean it would make the code more simple, that would be more or less the same, it would make the mental side of "how do I easily get some service into every DAL class?" an easy answer; inject it.
I know you said you don't want to change the constructor. That's cool, you don't want to change it because it is a pain to change all the places of instantiation.
However, if everything were being created by IoC, you would not care about adding to constructors because you would never invoke them directly.
Then, you could add services like your new IConnectionStringProvider right to the constructor and be done with it.

Exists only to defeat instantiation in singleton

In many of the Singleton examples, I have come across constructor having comment as "Exists only to defeat instantiation", can you please give me details and explain more about it.
It's common to create a private constructor when implementing the Singleton pattern so that the default constructor cannot be used to instantiate multiple Singleton objects.
See the example from Wikipedia's Singleton pattern article.
public class SingletonDemo {
private static SingletonDemo instance = null;
private SingletonDemo() { }
public static synchronized SingletonDemo getInstance() {
if (instance == null) {
instance = new SingletonDemo ();
}
return instance;
}
}
By making a private constructor, you insure that the compiler can't make a default constructor with the same signature, which forces any client code to call the getInstance() method.

ChannelFactory: creating and disposing

I have written an Sdk that is used by a WPF client, and takes care of calling WCF services and caching. These WCF services are called using the ChannelFactory, so I don't have service references. To do that, I created a factory that handles opening and closing ChannelFactory and ClientChannel as follows:
public class ProjectStudioServiceFactory : IDisposable
{
private IProjectStudioService _projectStudioService;
private static ChannelFactory<IProjectStudioService> _channelFactory;
public IProjectStudioService Instance
{
get
{
if (_channelFactory==null) _channelFactory = new ChannelFactory<IProjectStudioService>("ProjectStudioServiceEndPoint");
_projectStudioService = _channelFactory.CreateChannel();
((IClientChannel)_projectStudioService).Open();
return _projectStudioService;
}
}
public void Dispose()
{
((IClientChannel)_projectStudioService).Close();
_channelFactory.Close();
}
}
And each request I call like:
using (var projectStudioService = new ProjectStudioServiceFactory())
{
return projectStudioService.Instance.FindAllCities(new FindAllCitiesRequest()).Cities;
}
Although this works, it's slow because for every request the client channel and factory is opened and closed. If I keep it open, it's very fast. But I was wondering what the best practise would be? Should I keep it open? Or not? How to handle this in a correct way?
Thanks Daniel, didn't see that post. So I guess that the following may be a good approach:
public class ProjectStudioServiceFactory : IDisposable
{
private static IProjectStudioService _projectStudioService;
private static ChannelFactory<IProjectStudioService> _channelFactory;
public IProjectStudioService Instance
{
get
{
if (_projectStudioService == null)
{
_channelFactory = new ChannelFactory<IProjectStudioService>("ProjectStudioServiceEndPoint");
_projectStudioService = _channelFactory.CreateChannel();
((IClientChannel)_projectStudioService).Open();
}
return _projectStudioService;
}
}
public void Dispose()
{
//((IClientChannel)_projectStudioService).Close();
//_channelFactory.Close();
}
}

Where to store data for current WCF call? Is ThreadStatic safe?

While my service executes, many classes will need to access User.Current (that is my own User class). Can I safely store _currentUser in a [ThreadStatic] variable? Does WCF reuse its threads? If that is the case, when will it clean-up the ThreadStatic data? If using ThreadStatic is not safe, where should I put that data? Is there a place inside OperationContext.Current where I can store that kind of data?
Edit 12/14/2009: I can assert that using a ThreadStatic variable is not safe. WCF threads are in a thread pool and the ThreadStatic variable are never reinitialized.
There's a blog post which suggests implementing an IExtension<T>. You may also take a look at this discussion.
Here's a suggested implementation:
public class WcfOperationContext : IExtension<OperationContext>
{
private readonly IDictionary<string, object> items;
private WcfOperationContext()
{
items = new Dictionary<string, object>();
}
public IDictionary<string, object> Items
{
get { return items; }
}
public static WcfOperationContext Current
{
get
{
WcfOperationContext context = OperationContext.Current.Extensions.Find<WcfOperationContext>();
if (context == null)
{
context = new WcfOperationContext();
OperationContext.Current.Extensions.Add(context);
}
return context;
}
}
public void Attach(OperationContext owner) { }
public void Detach(OperationContext owner) { }
}
Which you could use like that:
WcfOperationContext.Current.Items["user"] = _currentUser;
var user = WcfOperationContext.Current.Items["user"] as MyUser;
An alternative solution without adding extra drived class.
OperationContext operationContext = OperationContext.Current;
operationContext.IncomingMessageProperties.Add("SessionKey", "ABCDEFG");
To get the value
var ccc = aaa.IncomingMessageProperties["SessionKey"];
That's it
I found that we miss the data or current context when we make async call with multiple thread switching. To handle such scenario you can try to use CallContext. It's supposed to be used in .NET remoting but it should also work in such scenario.
Set the data in the CallContext:
DataObject data = new DataObject() { RequestId = "1234" };
CallContext.SetData("DataSet", data);
Retrieving shared data from the CallContext:
var data = CallContext.GetData("DataSet") as DataObject;
// Shared data object has to implement ILogicalThreadAffinative
public class DataObject : ILogicalThreadAffinative
{
public string Message { get; set; }
public string Status { get; set; }
}
Why ILogicalThreadAffinative ?
When a remote method call is made to an object in another AppDomain,the current CallContext class generates a LogicalCallContext that travels along with the call to the remote location.
Only objects that expose the ILogicalThreadAffinative interface and are stored in the CallContext are propagated outside the AppDomain.

IDisposable base class which owns managed disposable resource, what to do in subclasses?

I have a base class that owns a managed disposable resource (.NET PerformanceCounter). I understand about implementing IDisposable on the class so that I can explicitly call Dispose on the resource. From the examples I have seen, people typically use a private boolean member variable "disposed" and set it to true inside of Dispose. Later, if there is an attempt to access a public method or property, an ObjectDisposedException is raised if "disposed" is true.
What about in the subclasses? How would the subclasses, in their public methods and properties, know that that they had been disposed? At first I thought that the subclasses would not have to anything special (like implement their own version of Dispose) since the thing that needs to be disposed is only in the base class (let's assume that the subclasses won't be adding any data that needs to be explicitly disposed) and the base class' Dispose should handle that. Should the subclasses override the base class' virtual Dispose method solely for the purpose of setting its own "disposed" member variable?
Here is a very stripped-down version of the class hierarchy in question.
class BaseCounter : IBaseCounter, IDisposable
{
protected System.Diagnostics.PerformanceCounter pc;
private bool disposed;
public BaseCounter(string name)
{
disposed = false;
pc = CreatePerformanceCounter(name);
}
#region IBaseCounter
public string Name
{
get
{
if (disposed) throw new ObjectDisposedException("object has been disposed");
return pc.CounterName;
}
}
public string InstanceName
{
get
{
if (disposed) throw new ObjectDisposedException("object has been disposed");
return pc.InstanceName;
}
}
#endregion IBaseCounter
#region IDisposable
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (pc != null)
{
pc.Dispose();
}
pc = null;
disposed = true;
}
}
}
public void Dispose()
{
Dispose(true);
}
#endregion IDisposable
}
class ReadableCounter : BaseCounter, IReadableCounter //my own interface
{
public ReadableCounter(string name)
: base(name)
{
}
#region IReadableCounter
public Int64 CounterValue()
{
return pc.RawValue;
}
#endregion IReadableCounter
}
class WritableCounter : BaseCounter, IWritableCounter
{
public WritableCounter(string name)
: base(name)
{
}
#region IWritableCounter
public Increment()
{
pc.Increment();
}
#endregion IWritableCounter
}
In our system, ReadableCounter and WritableCounter are the only subclasses of BaseCounter and they are only subclassed to one more level via a code generation processes. The additional subclassing level only addes a specific name so that it becomes possible to create objects that correspond directly to named counters (e.g. if there is a counter that is used to count the number of widgets produced, it ends up being encapsulated in a WidgetCounter class. WidgetCounter contains the knowledge (really, just the counter name as a string) to allow the "WidgetCounter" performance counter to be created.
Only the code-generated classes are used directly by developers, so we would have something like this:
class WritableWidgetCounter : WritableCounter
{
public WritableWidgetCounter
: base ("WidgetCounter")
{
}
}
class ReadableWidgetCounter : ReadableCounter
{
public ReadableWidgetCounter
: base ("WidgetCounter")
{
}
}
So, you see that the base class owns and manages the PerformanceCounter object (which is disposable) while the subclasses use the PerformanceCounter.
If I have code like this:
IWritableCounter wc = new WritableWidgetCounter();
wc.Increment();
wc.Dispose();
wc.Increment();
wc = null;
How could WritableCounter know, in Increment, that it had been disposed? Should ReadableCoutner and WritableCounter simply override the BaseCounter's
protected virtual void Dispose(bool disposing)
something like this:
protected virtual void Dispose(bool disposing)
{
disposed = true; //Nothing to dispose, simply remember being disposed
base.Dispose(disposing); //delegate to base
}
simply to set a ReadableCounter/WritableCounter-level "disposed" member variable?
How about if the base class (BaseCounter) declared disposed as protected (or made it a protected property)? That way, the subclasses could refer to it rather than adding a Dispose method simply for the purpose of remembering that Dispose had happened.
Am I missing the boat on this?
I have seen some disposable classes with a public IsDisposed property. You could do that and check it in your sub-classes.
Another thing I've done is a generic protected 'Validate' method that all sub-class methods call (and could override). If it returns, all is well, otherwise it might throw. That would insulate your sub-classes from the disposable innards altogether.
I have snippets that I use for implementing IDisposable, both in the base class and in the subclasses. You'd probably want the one for the subclass.
I swiped most of this code from MSDN, I think.
Here's the code for the base class IDisposable (not the one you want):
#region IDisposable Members
// Track whether Dispose has been called.
private bool _disposed = false;
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this._disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// TODO: Dispose managed resources.
}
// Release unmanaged resources. If disposing is false,
// only the following code is executed.
// TODO: Release unmanaged resources
// Note that this is not thread safe.
// Another thread could start disposing the object
// after the managed resources are disposed,
// but before the disposed flag is set to true.
// If thread safety is necessary, it must be
// implemented by the client.
}
_disposed = true;
}
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~Program()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
#endregion
And here's the code I use in the subclasses (this is the code you want):
#region IDisposable Members
// Track whether Dispose has been called.
private bool _disposed = false;
// Design pattern for a derived class.
// Note that this derived class inherently implements the
// IDisposable interface because it is implemented in the base class.
// This derived class does not have a Finalize method
// or a Dispose method without parameters because it inherits
// them from the base class.
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
try
{
if (disposing)
{
// Release the managed resources you added in
// this derived class here.
// TODO: Dispose managed resources.
}
// Release the native unmanaged resources you added
// in this derived class here.
// TODO: Release unmanaged resources.
_disposed = true;
}
finally
{
// Call Dispose on your base class.
base.Dispose(disposing);
}
}
}
#endregion
Look for the TODO: marks.