private static Dictionary<Type, Type> mappings;
public static TContract GetService<TContract>()
where TContract : class
{
string file = Path.Combine(GetProjectPath(EnvironmentMode.UnitTests), "ServiceLocator.xml");
// Check for configuration file:
if(!File.Exists(file))
throw new FileNotFoundException("Service Locator configuration file not found.");
// Load the configuration.
var configMappingElements = XElement.Load(file).Element("mappings").Elements("mapping");
var map = configMappingElements.Select(elem => ContractTypeMapping(elem));
mappings = map.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// Instantiate the type and return it to the caller.
return (TContract)Activator.CreateInstance(mappings[typeof(TContract)]);
}
private static KeyValuePair<Type, Type> ContractTypeMapping(XElement element)
{
var contract = Type.GetType(element.Attribute("contract").Value);
var implementation = Type.GetType(element.Attribute("type").Value);
return new KeyValuePair<Type, Type>(contract, implementation);
}