As a disclaimer I shall say that I'm still trying to wrap my head around the whole DI pattern therefore I guess it's needless to say that my code might probably have a major conceptual bug.
With that, what I'm trying to do is inject two properties on the following implementation:
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();
}
}
So when I call the method:
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);
}
}
}
Surprisingly for me it outputs:
"Peter Gibbons painted with oil on {0}"
It looks like everything is resolving fine, but do you mean for Oil.Apply()
to use string.Format()
?
class Oil : IMaterial
{
public string Apply(string surface)
{
return string.Format("painted with oil on {0}", surface);
}
}
This should return "Peter Gibbons painted with oil on canvas".
精彩评论