2010-12-05 70 views
1

作爲一個免責聲明,我會說我仍然試圖圍繞整個DI模式進行包裝,因此我猜想不必說我的代碼可能會有一個重大的概念錯誤。使用Ninject進行多重依賴注入的問題

就這樣,我想要做的是對下列實施注入兩個屬性:

interface ISurface 
{ 
    string Use(); 
} 

class Canvas : ISurface 
{ 
    public string Use() 
    { 
     return "canvas"; 
    } 
} 

class Hardboard : ISurface 
{ 
    public string Use() 
    { 
     return "hardboard"; 
    } 
} 

interface IMaterial 
{ 
    string Apply(string surface); 
} 

class Oil : IMaterial 
{ 
    public string Apply(string surface) 
    { 
     return "painted with oil on {0}"; 
    } 
} 

class Acrylic : IMaterial 
{ 
    public string Apply(string surface) 
    { 
     return "painted with acrylic on {0}"; 
    } 
} 

class Artist 
{ 
    public string Name { get; set; } 

    [Inject] 
    public IMaterial Material { get; set; } 

    [Inject] 
    public ISurface Surface { get; set; } 

    public string Paint() 
    { 
     return Material.Apply(Surface.Use()); 
    } 
} 

class PainterModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<ISurface>().To<Canvas>(); 
     Bind<IMaterial>().To<Oil>(); 
     Bind<Artist>().ToSelf(); 
    } 
} 

所以,當我打電話的方法:

class Program 
{ 
    static void Main(string[] args) 
    { 
     try 
     { 
      IKernel kernel = new StandardKernel(new PainterModule()); 
      Artist artist = kernel.Get<Artist>(); 
      artist.Name = "Peter Gibbons"; 
      Console.WriteLine(artist.Name + artist.Paint()); 
     } 
     catch (Exception error) 
     { 
      Console.WriteLine(error.Message); 
      throw; 
     } 
     finally 
     { 
      Console.ReadKey(true); 
     } 
    } 
} 

令人驚訝的對我來說,輸出:

​​

回答

1

它看起來像一切都解決好,但你的意思是爲Oil.Apply()使用string.Format()

class Oil : IMaterial 
{ 
    public string Apply(string surface) 
    { 
     return string.Format("painted with oil on {0}", surface); 
    } 
} 

這應該會返回「彼得吉本斯在畫布上塗油」。

+0

哇 - 我是一個白癡:)非常感謝dahlbyk! – 2010-12-05 21:10:40