标签:
将Autofac集成到应用程序的基本模式是:
本开始向导通过一个简单的控制台程序来向你介绍以上步骤。一旦有了一定的基础,你可以查看wiki的其他部分来了解更多高级用法以及对于WCF, ASP.NET和其它应用类型的集成方法。
控制反转背后的思想是,在类的构造期间传递依赖而不是在应用程序里将这些类绑在一起让类自己创建他们的依赖。如果想了解更多,你可以查看Martin Fowler的一篇解释依赖注入/控制反转的优秀文章。
我们的示例程序中,定义一个输入当前日期的类。然而我们不想将这个类同控制台绑定,因为我们想在以后控制台不可用的条件下也能测试这个类。
我们尽量使用抽象机制来写这个类,这样如果我们想要将其替换成一个输出明天日期的版本将会很容易实现。
我们将这样做:
using System; namespace DemoApp { // This interface helps decouple the concept of // "writing output" from the Console class. We // don‘t really "care" how the Write operation // happens, just that we can write. public interface IOutput { void Write(string content); } // This implementation of the IOutput interface // is actually how we write to the Console. Technically // we could also implement IOutput to write to Debug // or Trace... or anywhere else. public class ConsoleOutput : IOutput { public void Write(string content) { Console.WriteLine(content); } } // This interface decouples the notion of writing // a date from the actual mechanism that performs // the writing. Like with IOutput, the process // is abstracted behind an interface. public interface IDateWriter { void WriteDate(); } // This TodayWriter is where it all comes together. // Notice it takes a constructor parameter of type // IOutput - that lets the writer write to anywhere // based on the implementation. Further, it implements // WriteDate such that today‘s date is written out; // you could have one that writes in a different format // or a different date. public class TodayWriter : IDateWriter { private IOutput _output; public TodayWriter(IOutput output) { this._output = output; } public void WriteDate() { this._output.Write(DateTime.Today.ToShortDateString()); } } }
标签:
原文地址:http://www.cnblogs.com/chenghyi/p/5513083.html