我正在寻找有关 DI 的简单“Hello World”示例的帮助。我不明白的是如何在 DI 框架(autofac)中初始化“Foo”和“Bar”类。
namespace AutofacTesting
{
//these classes are intended to be used with autofac / DI
public interface IFooBar
{
void Draw();
}
public class Bar : IFooBar
{
public void Draw()
{
MessageBox.Show("Drawing something in Bar");
}
}
public class Foo : IFooBar
{
public void Draw()
{
MessageBox.Show("Drawing somthing in Foo");
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
builder.RegisterType<Bar>().As<IFooBar>();
builder.RegisterType<Foo>().As<IFooBar>();
var container = builder.Build();
var taskController = container.Resolve<IFooBar>();
taskController.Draw();
int a = 1;
}
}
}