【发布时间】:2013-11-04 18:55:48
【问题描述】:
我有一个带有许多自定义服务器控件的 ASP.Net Web 应用程序。
很遗憾,Ninject could not inject dependency into CompositeControls。
我是 Ninject 的新手;以下是我解决问题的简单方法。
由于我有许多自定义服务器控件,我最终将创建多个 StandardKernel 实例。
这是一个糟糕的设计吗? 如果我错了,请纠正我。谢谢!
public interface ICalculate
{
int Add(int x, int y);
}
public class Calculate : ICalculate
{
public int Add(int x, int y)
{
return x + y;
}
}
public class DemoModule : NinjectModule
{
public override void Load()
{
Bind<ICalculate>().To<Calculate>();
}
}
public class MyServerControl : CompositeControl
{
private TextBox TextBox1;
private TextBox TextBox2;
private Label Label1;
public ICalculate Calculate { get; set; }
public MyServerControl()
{
IKernel kernel = new StandardKernel(new DemoModule());
Calculate = kernel.Get<ICalculate>();
}
protected override void CreateChildControls()
{
TextBox1 = new TextBox{ID = "TextBox1", Text = "1"};
Controls.Add(TextBox1);
TextBox2 = new TextBox {ID = "TextBox2", Text = "2"};
Controls.Add(TextBox2);
var button1 = new Button {ID = "Button1", Text = "Calculate"};
button1.Click += button1_Click;
Controls.Add(button1);
Label1 = new Label {ID = "Label1"};
Controls.Add(Label1);
}
private void button1_Click(object sender, EventArgs e)
{
int value1 = Int32.Parse(TextBox1.Text);
int value2 = Int32.Parse(TextBox2.Text);
Label1.Text = "Result:" + Calculate.Add(value1,value2);
}
}
【问题讨论】:
-
看看我对你其他问题的回答。
-
创建多个实例看起来不错,但是创建无限数量的实例(例如每个 Web 请求一个,甚至每个请求多个)是一个非常糟糕的主意,因为性能实现.然而,一般的经验法则是只为整个应用程序创建一个实例。
标签: c# asp.net dependency-injection ninject inversion-of-control