Created
December 1, 2015 14:29
-
-
Save miroslavpopovic/494a764ac420d6e3cc06 to your computer and use it in GitHub Desktop.
Inject dictionary of interfaces with Ninject
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Ninject; | |
namespace ConsoleApplication5 | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var kernel = new StandardKernel(); | |
// First we create named bindings for ISerializer service | |
kernel.Bind<ISerializer>().To<CsvSerializer>().Named("csv"); | |
kernel.Bind<ISerializer>().To<DatabaseSerializer>().Named("database"); | |
// Next, we bind all of them as a dictionary, so that dictionary can be used as a constructor argument | |
// - Binding name will be the key of the item in a dictionary | |
// - Service instance will be the value of the item in a dictionary | |
kernel.Bind<IDictionary<string, ISerializer>>().ToMethod( | |
context => kernel.GetBindings(typeof (ISerializer)) | |
.ToDictionary( | |
binding => binding.Metadata.Name, | |
binding => (ISerializer) kernel.Get(binding.Service, binding.Metadata.Name))); | |
// Now we bind Consumer class, so we can get an instance of it | |
kernel.Bind<Consumer>().ToSelf(); | |
var consumer = kernel.Get<Consumer>(); | |
consumer.Serialize(); | |
Console.ReadLine(); | |
} | |
} | |
public interface ISerializer | |
{ | |
string Serialize(); | |
} | |
public class CsvSerializer : ISerializer | |
{ | |
public string Serialize() => "csv serialized"; | |
} | |
public class DatabaseSerializer : ISerializer | |
{ | |
public string Serialize() => "database serialized"; | |
} | |
public class Consumer | |
{ | |
private readonly IDictionary<string, ISerializer> _serializers; | |
public Consumer(IDictionary<string, ISerializer> serializers) | |
{ | |
_serializers = serializers; | |
} | |
public void Serialize() | |
{ | |
var csvResult = _serializers["csv"].Serialize(); | |
Console.WriteLine(csvResult); | |
var databaseResult = _serializers["database"].Serialize(); | |
Console.WriteLine(databaseResult); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment