Advertisement
Guest User

Untitled

a guest
Dec 1st, 2015
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Ninject;
  5.  
  6. namespace ConsoleApplication5
  7. {
  8. public class Program
  9. {
  10. public static void Main(string[] args)
  11. {
  12. var kernel = new StandardKernel();
  13.  
  14. // First we create named bindings for ISerializer service
  15. kernel.Bind<ISerializer>().To<CsvSerializer>().Named("csv");
  16. kernel.Bind<ISerializer>().To<DatabaseSerializer>().Named("database");
  17.  
  18. // Next, we bind all of them as a dictionary, so that dictionary can be used as a constructor argument
  19. // - Binding name will be the key of the item in a dictionary
  20. // - Service instance will be the value of the item in a dictionary
  21. kernel.Bind<IDictionary<string, ISerializer>>().ToMethod(
  22. context => kernel.GetBindings(typeof (ISerializer))
  23. .ToDictionary(
  24. binding => binding.Metadata.Name,
  25. binding => (ISerializer) kernel.Get(binding.Service, binding.Metadata.Name)));
  26.  
  27. // Now we bind Consumer class, so we can get an instance of it
  28. kernel.Bind<Consumer>().ToSelf();
  29.  
  30. var consumer = kernel.Get<Consumer>();
  31. consumer.Serialize();
  32.  
  33. Console.ReadLine();
  34. }
  35. }
  36.  
  37. public interface ISerializer
  38. {
  39. string Serialize();
  40. }
  41.  
  42. public class CsvSerializer : ISerializer
  43. {
  44. public string Serialize() => "csv serialized";
  45. }
  46.  
  47. public class DatabaseSerializer : ISerializer
  48. {
  49. public string Serialize() => "database serialized";
  50. }
  51.  
  52. public class Consumer
  53. {
  54. private readonly IDictionary<string, ISerializer> _serializers;
  55.  
  56. public Consumer(IDictionary<string, ISerializer> serializers)
  57. {
  58. _serializers = serializers;
  59. }
  60.  
  61. public void Serialize()
  62. {
  63. var csvResult = _serializers["csv"].Serialize();
  64. Console.WriteLine(csvResult);
  65.  
  66. var databaseResult = _serializers["database"].Serialize();
  67. Console.WriteLine(databaseResult);
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement