2010-12-05 13 views
1

免責事項として、私はまだDIパターン全体を頭で覆そうとしていますので、私のコードに大きな概念的バグがあるとは言えません。それは出力私にとって驚くべきことにNinjectを使用した複数依存性注入の問題

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); 
     } 
    } 
} 

:私はメソッドを呼び出すときに

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(); 
    } 
} 

:それと

は、私がやろうとしていることは、次の実装上の2つのプロパティを注入しています。

​​

答えて

1

すべての問題は解決しているようですが、Oil.Apply()string.Format()を使用しますか?

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

「キャンバスに油で塗装されたピーター・ギボンズ」が返されます。

+0

うわー - 私はばかです:)ありがとうdahlbyk! –

関連する問題