2010-12-05 58 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