我有一个带有许多自定义服务器控件的 ASP.Net Web 应用程序。
不幸的是,Ninject 无法将依赖项注入到 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);
}
}