2013-02-17 12 views
1

我需要掃描所有組件。(從抽象類ColorTest繼承或類)具有特定屬性的類和全自動它們綁定到ColorTest。 然後我需要實例化和枚舉ColorTest掃描組件和自動捆綁基於類註解或繼承類型

組件1的所有實現:

public abstract class ColorTest { 
    public abstract string GetColorString(); 
} 

組件2:

//[ColorImplementation] // attributes are not necessary 
public class BlueColor() : ColorTest {...} 

大會3:

//[ColorImplementation] //not necessary 
public class RedColor() : ColorTest {...} 

組裝4 :

class Program{ 
    public static Main(){ 

     #region Problem area :) 
     var kernel = new StandardKernel(); 

     kernel.Bind(x => x 
      .FromAssembliesMatching("*") 
      .SelectAllClasses() 
      .InheritedFrom<ColorTest>// or .WithAttribute<ObsoleteAttribute>() 
      .BindAllInterfaces() // I'd like to Bind it only to ColorTest 
      .Configure(b => b.InSingletonScope())); 
     #endregion 

     // Enumerate 
     kernel 
      .GetAll<ColorTest>() 
      .ToList() 
      .ForEach(t=>Console.WriteLine(t.GetColorString())); 
} 

實施例是更復雜的問題的抽象&簡化。

Can Ninject可以幫我處理上述場景嗎?如果是的話如何?

回答

1

解決方案非常簡單!

我不得不更換2號線:

.FromAssembliesMatching("*") -> .FromAssembliesMatching(".") //mistake 

.BindAllInterfaces() -> .BindBase() // because I'm implementing 
            // abstract class, not interface 

屬性並沒有參與