PageRenderTime 35ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/CommonServiceLocator/CommonServiceLocator.LinFuAdapter/LinFuServiceLocator.cs

http://github.com/philiplaureano/LinFu
C# | 58 lines | 46 code | 11 blank | 1 comment | 12 complexity | ebb6c00309fcb420d828dfdcb4e6ca8d MD5 | raw file
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using LinFu.IoC;
  6. using LinFu.IoC.Configuration;
  7. using LinFu.IoC.Interfaces;
  8. using Microsoft.Practices.ServiceLocation;
  9. namespace CommonServiceLocator.LinFuAdapter
  10. {
  11. public sealed class LinFuServiceLocator : ServiceLocatorImplBase
  12. {
  13. readonly IServiceContainer _container;
  14. public LinFuServiceLocator(IServiceContainer container)
  15. {
  16. if (container == null)
  17. throw new ArgumentNullException("container");
  18. _container = container;
  19. }
  20. protected override object DoGetInstance(Type serviceType, string key)
  21. {
  22. if (key != null)
  23. return _container.GetService(key, serviceType);
  24. // Return the first service if nothing else can be found
  25. Func<IServiceInfo, bool> criteria = info =>
  26. {
  27. var matchesServiceType = info.ServiceType == serviceType;
  28. if (!matchesServiceType)
  29. return false;
  30. return info.ArgumentTypes == null || info.ArgumentTypes.Count() == 0;
  31. };
  32. var defaultService = _container.AvailableServices.Where(criteria).FirstOrDefault();
  33. return _container.GetService(defaultService);
  34. }
  35. protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
  36. {
  37. Func<IServiceInfo, bool> matchesServiceType = info => serviceType == info.ServiceType &&
  38. (info.ArgumentTypes == null ||
  39. info.ArgumentTypes.Count() == 0);
  40. var services = _container.AvailableServices.Where(matchesServiceType);
  41. foreach (var service in services)
  42. {
  43. yield return _container.GetService(service);
  44. }
  45. }
  46. }
  47. }