Skip to content

Instantly share code, notes, and snippets.

@robcthegeek
Created May 24, 2011 16:52
Show Gist options
  • Save robcthegeek/989100 to your computer and use it in GitHub Desktop.
Save robcthegeek/989100 to your computer and use it in GitHub Desktop.
Dealing with PITA Singletons that aren't thread safe.
public class MyService
{
private Func<IDep1> Dep1Factory;
private Func<IDep2> Dep2Factory;
IDep1 Dep1 { get { return Dep1Factory(); } }
IDep2 Dep2 { get { return Dep2Factory(); } }
public MyService()
{
// Default ctor, required by runtime
// Set up how we are going to retrieve the instances
Dep1Factory = () => ServiceLocator.Get<IDep1>();
Dep2Factory = () => ServiceLocator.Get<IDep2>();
// If the Singleton is not thread-safe, then you can tell your IoC container
// (which is called by the Service Locator) to mark it in current thread/request scope.
}
public MyService(IDep1 dep1, IDep2 dep2)
{
Dep1Factory = () => dep1;
Dep2Factory = () => dep2;
}
public SomeMethodUsingDeps()
{
Dep1.DoSomething();
Dep2.DoSomethingElse();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment