作为免责声明,我会说我仍然试图绕过整个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}"
答案 0 :(得分:1)
看起来好像一切都很好,但是你的意思是Oil.Apply()
使用string.Format()
吗?
class Oil : IMaterial
{
public string Apply(string surface)
{
return string.Format("painted with oil on {0}", surface);
}
}
这应该归还“彼得吉本斯用油画布画”。