[英]Problem with multiple dependency injection using Ninject
作為免責聲明,我要說的是我仍在努力將整個DI模式包裹在頭上,因此,我想不必說我的代碼可能有一個主要的概念性錯誤。
這樣,我想要做的就是在以下實現中注入兩個屬性:
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);
}
}
}
令我驚訝的是,它輸出:
"Peter Gibbons painted with oil on {0}"
看起來一切都很好,但您是要Oil.Apply()
使用string.Format()
嗎?
class Oil : IMaterial
{
public string Apply(string surface)
{
return string.Format("painted with oil on {0}", surface);
}
}
這應該返回“在畫布上塗油的彼得·吉本斯”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.