前段时间也研究了其他IOC框架,如unity、Castle、Autofac,相对来说Autofac比较简单,据说也是效率最高的。首先了解下控制反转和依赖注入 IoC把创建依赖对象的控制权交给了容器,由容器进行注入对象,所以对象与对象之间是松散耦合,利于功能复用,也使得程序的整个体系结构变得非常灵活。
控制反转Ioc:调用者不主动创建被调用者实例,由IoC容器来创建;
依赖注入DI:把依赖关系注入到调用者;
Autofac+Mvc4 项目架构
Student.cs实体
1 public class Student 2 { 3 public string name { get; set; } 4 public int age { get; set; } 5 public string gender { get; set; } 6 }
IStudentRepository.cs接口
1 public interface IStudentRepository 2 { 3 IEnumerable<Student> GetAll(); 4 }
StudentRepository实现接口
1 public class StudentRepository : IStudentRepository 2 { 3 private List<Student> Articles = new List<Student>(){ 4 new Student { name = "张三", gender = "male", age = 12 }, 5 new Student { name = "李四", gender = "fmale", age = 15 }, 6 new Student { name = "王五", gender = "fmale", age = 13 }}; 7 8 /// <summary> 9 /// 获取全部学生信息 10 /// </summary> 11 /// <returns></returns> 12 public IEnumerable<Student> GetAll() 13 { 14 return Articles; 15 } 16 }
HomeControll.cs控制器
1 #region [AutoFac注入] 2 3 readonly IStudentRepository repository; 4 //构造器注入 5 public HomeController(IStudentRepository repository) 6 { 7 this.repository = repository; 8 } 9 10 /// <summary> 11 /// AutoFac注入 12 /// </summary> 13 /// <returns></returns> 14 public ActionResult StudentIndex() 15 { 16 var data = repository.GetAll(); 17 return View(data); 18 } 19 #endregion
在App_Start文件夹中添加AutofacConfig.cs文件
1 public class AutofacConfig 2 { 3 /// <summary> 4 /// 负责调用autofac框架实现业务逻辑层和数据仓储层程序集中的类型对象的创建 5 /// 负责创建MVC控制器类的对象(调用控制器中的有参构造函数) 6 /// </summary> 7 public static void Register() 8 { 9 ContainerBuilder builder = new ContainerBuilder(); 10 SetupResolveRules(builder); 11 builder.RegisterControllers(Assembly.GetExecutingAssembly()); 12 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces(); 13 var container = builder.Build(); 14 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 15 16 } 17 /// <summary> 18 /// 所有需要注入的类型 19 /// </summary> 20 /// <param name="builder"></param> 21 private static void SetupResolveRules(ContainerBuilder builder) 22 { 23 builder.RegisterType<StudentRepository>().As<IStudentRepository>(); 24 } 25 }
在Global.asax.cs类Application_Start方法中注册Autofac
1 public class MvcApplication : System.Web.HttpApplication 2 { 3 protected void Application_Start() 4 { 5 AreaRegistration.RegisterAllAreas(); 6 7 WebApiConfig.Register(GlobalConfiguration.Configuration); 8 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 9 RouteConfig.RegisterRoutes(RouteTable.Routes); 10 BundleConfig.RegisterBundles(BundleTable.Bundles); 11 12 AutofacConfig.Register();//AutoFac注入 13 } 14 }
执行程序返回数据
可以参考http://www.cnblogs.com/bubugao/p/AutofacDemo.html文章,简单明了解释Autofac作用。