1.首先需要安裝 Autofac 和Autofac.Integration.Mvc
install-package Autofac -version5.2.0
install-package Autofac.Integration.Mvc -version 5.0.0
2.編寫依賴注入和解析器類,并在該類中增加靜态方法,實作注入和依賴解析,通過
System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
來把目前的依賴注入加入到mvc架構中。
說明:
- DependencyResolver 是System.Web.Mvc 命名空間中的類,其方法SetResolver()接收一個IDependencyResolver接口類型的參數;
- AutofacDependencyResolver 是Autofac.Integration.Mvc命名空間中的類,該類實作了IDependencyResolver方法,在該類中隻是把IDependencyResolver接口的兩個方法GetService()和GetServices()作為虛拟方法,并未真正實作。該類是通過多個重載的構造函數來實作其生命周期的控制,并且至少接收一個ILifetimeScope類型注入容器參數來實作依賴項的解析。
3.為了使依賴解析器能夠在系統啟動時啟動,需要在Global.asax.cs 中調用依賴解析器類中的靜态方法進行初始化。
4. 控制器抽象,重建一個控制器基類,并在其中增加以來注入對象擷取的方法,根據傳入的接口類型自動比對注入的依賴,進而得到該接口的執行個體。其他控制器通過繼承該類而共享該類方法來擷取依賴解析對象。
示例正代碼:
1.倉儲接口
using autofacdemo2.Models;
using System.Collections.Generic;
namespace autofacdemo2.Repository
{
public interface IStudentRepository
{
List<Student> GetStudents();
}
}
2.倉儲實作
public class StudentRepository : IStudentRepository
private List<Student> students;
public StudentRepository()
{
students = new List<Student> {
new Student{ Id=1,Name="張三",Sex="男",Grade="二(一)班" },
new Student{ Id=2,Name="李四",Sex="女",Grade="二(二)班" },
new Student{ Id=3,Name="王五",Sex="男",Grade="二(一)班" }
};
}
public List<Student> GetStudents()
return students;
3.依賴解析類
using Autofac;
using Autofac.Integration.Mvc;
using autofacdemo2.Repository;
using System.Web.Mvc;
namespace autofacdemo2.App_Start
public class DependencyInject
private static IContainer _container;
public static IContainer Container {
get { return _container; }
/// <summary>
/// 注冊相關接口
/// </summary>
public static void Initialise()
var builder = new ContainerBuilder();
builder.RegisterType<StudentRepository>().As<IStudentRepository>();
_container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
4.控制器
using System.Linq;
namespace autofacdemo2.Controllers
public class HomeController : Controller
protected internal IStudentRepository GetStudentRepository()
return DependencyResolver.Current.GetService<IStudentRepository>();
// GET: Home
public ActionResult Index()
var students = GetStudentRepository();
ViewBag.Count = students.GetStudents().Count();
return View(students.GetStudents());
5.控制器基類
public class BasicController : Controller
// GET: Basic
protected internal TService GetService<TService>()
return DependencyResolver.Current.GetService<TService>();
6.控制器派生類
public class AutofacTestController : BasicController
// GET: AutofacTest
var studentrepository = GetService<IStudentRepository>();
ViewBag.Count = studentrepository.GetStudents().Count();
return View();