建立 空的 MVC4项目
首先引用 NuGet 里 autofac 和 autofac .integration. mvc
然后 建立Model
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
public interface IPersonRepository
{
IEnumerable GetAll();
Person Get(int id);
Person Add(Person item);
bool Update(Person item);
bool Delete(int id);
}
public class PersonRepository : IPersonRepository
{
List person = new List();
public PersonRepository()
{
Add(new Person { Id = 1, Name = "joye.net1", Age = 18, Address = "中国上海" });
Add(new Person { Id = 2, Name = "joye.net2", Age = 18, Address = "中国上海" });
Add(new Person { Id = 3, Name = "joye.net3", Age = 18, Address = "中国上海" });
}
public IEnumerable GetAll()
{
return person;
}
public Person Get(int id)
{
return person.Find(p => p.Id == id);
}
public Person Add(Person item)
{
if (item == null) { throw new ArgumentNullException("item"); }
person.Add(item);
return item;
}
public bool Update(Person item)
{
if (item == null) { throw new ArgumentNullException("item"); }
int index = person.FindIndex(p => p.Id == item.Id);
if (index == -1)
{
return false;
}
person.RemoveAt(index);
person.Add(item); return true;
}
public bool Delete(int id)
{
person.RemoveAll(p => p.Id == id);
return true;
}
}
再新建 HomeController 与相应的 Index.cshtml 在HomeController 声明 属性及构造函数
public class HomeController : Controller
{
public IPersonRepository _personRepository { get; set; }
public HomeController(IPersonRepository personRepository)
{
_personRepository = personRepository;
}
public ActionResult Index()
{
var item = _personRepository.Get(1);
return View();
}
}
最后在global.asax.cs 的Application_Start() 里实现注入
using Autofac;
using Autofac.Integration.Mvc;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var builder = new ContainerBuilder();
builder.RegisterType<PersonRepository>().As<IPersonRepository>(); //注册接口服务
builder.RegisterControllers(Assembly.GetExecutingAssembly());//构造函数注入
//builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();//属性注入
var container = builder.Build();//构建
System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//开始注入
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}