2012-04-26 39 views
2

我正在寻找DI的简单“Hello World”示例的一些帮助。我不明白的是如何在DI框架(autofac)中初始化类“Foo”和“Bar”。C#中的autofac“Hello World”应用程序 - 初始化

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; 
     } 
    } 
} 

回答

2

我想你的意思是你要解决一个BarFoo类作为具体实现,而不是实例化。如果是这样,你可以写:

var builder = new ContainerBuilder(); 

builder.RegisterType<Bar>().Named<IFooBar>("Bar"); 
builder.RegisterType<Foo>().Named<IFooBar>("Foo"); 

var container = builder.Build(); 

var taskController = container.ResolveNamed<IFooBar>("Bar"); 

taskController.Draw(); 

我也意识到这是一个Hello World应用程序,但要小心,不要失败到anti-pattern of using a service locator(即使用contain.Resolve所有的地方)。相反,请考虑允许您在同一地点进行所有注册和解决的设计,名称为composition root

我提到这个警告,因为这个级别的歧义(即为给定接口注册多个concreate类型)可能导致人们开始使用服务定位器模式。相反,在更复杂的应用程序中,请考虑重构您的API以避免解决注册类型时的歧义。