Posted By

streamt on 03/03/10


Tagged

container service provider


Versions (?)

Service Provider


 / Published in: C#
 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Services
  7. {
  8. public interface IService
  9. {
  10.  
  11. }
  12.  
  13. public interface IServiceProvider<T>
  14. {
  15. T GetService<T>();
  16. object GetService(Type serviceType);
  17. }
  18.  
  19. public sealed class ServiceProvider : IServiceProvider<IService>
  20. {
  21. private Dictionary<Type, object> _services;
  22.  
  23. private ServiceProvider()
  24. {
  25. _services = new Dictionary<Type, object>();
  26. }
  27.  
  28. public void RegisterService(Type type, object service)
  29. {
  30. if (!_services.ContainsKey(type))
  31. {
  32. _services.Add(type, service);
  33. }
  34. }
  35.  
  36. public T GetService<T>() where T : IService
  37. {
  38. return (T)_services[typeof(T)];
  39. }
  40.  
  41. public object GetService(Type serviceType)
  42. {
  43. return (_services.ContainsKey(serviceType)) ? _services[serviceType] : null;
  44. }
  45. }
  46. }
  47. }

Report this snippet  

You need to login to post a comment.