原文地址:https://www.cnblogs.com/yinrq/p/5381492.html
一、前言
Autofac是.NET领域最为流行的IOC框架之一,微软的Orchad开源程序使用的就是Autofac,Nopcommerce开源程序也是用的Autofac。
Orchad和Nopcommerce在用Autofac的时候进行封装,看过源码的都知道Autafac使用简单,功能强大。
建议下载Orchad和Nopcommerce学习下源码:附上下载地址
http://www.orchardproject.net/
和其他IOC对比:
Unity:微软patterns&practicest团队开发的IOC依赖注入框架,支持AOP横切关注点。
MEF(Managed Extensibility Framework):是一个用来扩展.NET应用程序的框架,可开发插件系统。
Spring.NET:依赖注入、面向方面编程(AOP)、数据访问抽象,、以及ASP.NET集成。
PostSharp:实现静态AOP横切关注点,使用简单,功能强大,对目标拦截的方法无需任何改动。
Autofac:最流行的依赖注入和IOC框架,轻量且高性能,对项目代码几乎无任何侵入性。
下面介绍Autofac的使用
二、Autofac使用
新建一个mvc的项目,使用nuget安装Autofac,需要安装Autofac和Autofac ASP.NET MVC5 Intergration
安装完成后引用里面就多了Autofac.dll和Autofac.Intergration.MVC,如果是在webApi里使用Autofac需要安装Autofac ASP.NET Web API2.2 Intergration 才可以。
新建一个person实体类
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
知识兔新建一个person仓储接口
public interface IPersonRepository
{
IEnumerable<Person> GetAll();
Person Get(int id);
Person Add(Person item);
bool Update(Person item);
bool Delete(int id);
}
知识兔