Created
May 24, 2011 16:52
-
-
Save robcthegeek/989100 to your computer and use it in GitHub Desktop.
Dealing with PITA Singletons that aren't thread safe.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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