There are extensions for ninject that handle things like xml configuration.
I would be careful about mixing the programming bits from config a la Spring XML config, although there is no need to go into the XML configuration to allow people to customize things in the .config file. I suggest reading the loader of the XML configuration section, which is serialized in a class that expresses this at a higher level.
You use the metadata mechanism in your bind registers, and then specify how to filter the task set based on this.
for example, reprogramming @ Ian Davis answer (read it and release now!):
string metaDataKey = "key"; kernel.Bind<IWeapon>().To<Shuriken>().WithMetadata(metaDataKey, true); kernel.Bind<IWeapon>().To<Sword>().WithMetadata(metaDataKey, false); kernel.Bind<IWeapon>().To<Knife>(); bool? theOneIWant = null;
If all you are looking for is their name, there is an abbreviated replacement for WithMetadata called Named() and an overload for .Get<T>() with a name string parameter, which allows you to achieve @dave a simple teeb, without your calls were tightly bound to type names.
EDIT: Example, see comments:
using Ninject; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace ninjectmess { public class Class1 {
Some classes of spam messages
public interface ITask { } public class Aasdsdaadsdsa : ITask { } public class Bdsadsadasdsadsadsa : ITask { } public class Cddsadasdsadasdas : ITask { }
actual test
[Fact] public void TestMethod() { var k = new StandardKernel(); k.Bind<ITask>().To<Aasdsdaadsdsa>().Named( "A" ); k.Bind<ITask>().To<Bdsadsadasdsadsadsa>().Named( "B" ); k.Bind<ITask>().To<Cddsadasdsadasdas>().Named( "C" ); var wanted = new string[] { "A", "C" }; var tasks = k .GetAll<ITask>( metadata => wanted.Contains( metadata.Name )) .ToList(); Assert.Equal( 2, tasks.Count ); tasks.ForEach( Console.WriteLine ); } } }
Ruben bartelink
source share