Autofac是一个轻量级的依赖注入的框架,同类型的框架还有Spring.NET,Unity,Castle等。
Autofac的使用有一个非常让人郁闷的地方,就是服务器要求安装有Microsoft .NET Framework 4 KB2468871。该补丁的地址是:http://www.microsoft.com/zh-cn/download/confirmation.aspx?id=3556 如果不安装,则运行程序会报如下错误:
具体信息可以到这里去查看:https://code.google.com/p/autofac/wiki/FrequentlyAskedQuestions
namespace ConsoleApplication3 { class Program { static void Main(string[] args) { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<AutoFacManager>(); builder.RegisterType<Worker>().As<IPerson>(); using (IContainer container = builder.Build()) { AutoFacManager manager = container.Resolve<AutoFacManager>(); manager.Say(); } Console.ReadKey(); } } public interface IPerson { void Say(); } public class Worker : IPerson { public void Say() { Console.WriteLine("我是一个工人!"); } } public class Student : IPerson { public void Say() { Console.WriteLine("我是一个学生!"); } } public class AutoFacManager { IPerson person; public AutoFacManager(IPerson MyPerson) { person = MyPerson; } public void Say() { person.Say(); } } }
时间: 2024-10-11 23:07:53