Created
October 29, 2013 19:56
-
-
Save gabrieljoelc/7221467 to your computer and use it in GitHub Desktop.
Mock service locator provider from http://joseoncode.com/2010/02/24/testing-code-that-use-servicelocator-servicelocatorstub/
This file contains hidden or 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 ServiceLocatorStub : ServiceLocatorImplBase | |
{ | |
private readonly IDictionary<Type, ICollection<object>> | |
registeredTypes = new Dictionary<Type, ICollection<object>>(); | |
private ServiceLocatorStub() | |
{} | |
public ServiceLocatorStub AddInstance<TService>(TService instance) | |
{ | |
ICollection<object> instanceCollection; | |
if(!registeredTypes.TryGetValue(typeof(TService), out instanceCollection)) | |
{ | |
instanceCollection = new List<object>(); | |
registeredTypes[typeof (TService)] = instanceCollection; | |
} | |
instanceCollection.Add(instance); | |
return this; | |
} | |
public static ServiceLocatorStub Create() | |
{ | |
var fakeServiceLocator = new ServiceLocatorStub(); | |
ServiceLocator.SetLocatorProvider(() => fakeServiceLocator); | |
return fakeServiceLocator; | |
} | |
protected override object DoGetInstance(Type serviceType, string key) | |
{ | |
return registeredTypes[serviceType].FirstOrDefault(); | |
} | |
protected override IEnumerable<object> DoGetAllInstances(Type serviceType) | |
{ | |
return registeredTypes[serviceType]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment