【发布时间】:2017-01-27 14:27:38
【问题描述】:
演示问题的示例解决方案:
class World
{
public override string ToString()
{
return "Hello World";
}
}
class Hello
{
[Inject]
public World theWorld { get; set; }
public Hello(IKernel kernel)
{
kernel.Inject(this);
}
public override string ToString()
{
return theWorld.ToString();
}
}
class Program
{
static IKernel kernel = new StandardKernel();
static void RegisterServices()
{
kernel.Bind<World>().ToSelf();
}
static void Main(string[] args)
{
RegisterServices();
Hello hello = new Hello(kernel);
Console.WriteLine(hello.ToString());
Console.ReadLine();
}
}
这就是我让属性注入真正起作用的方式。
如果出现以下情况,它将不起作用:
- 属性不是公开的(或其设置者)。
- 请求注入的类没有得到IKernel实例,调用
kernel.Inject(this);。
对我来说,仅仅为了获取一个属性的实例而这样做似乎是非常过分和错误的。有没有更简单的方法或者我没有考虑过什么?
【问题讨论】: