1. 程式人生 > >在MVC 中使用 autofac 實現自動註冊

在MVC 中使用 autofac 實現自動註冊

思路很簡單:首先我們去找到所有Dll,再去找到實現了IAutoInject 介面的類,然後使用RegisterAssemblyTypes進行注入。IAutoInject是一個空介面,用來輔助我們尋找需要註冊的介面

1. 在控制檯執行命令安裝AutoFac元件

  • Install-Package Autofac

  • Install-Package Autofac.Mvc5 -Version 4.0.2

2. 定義IAutoInject介面

 public interface IAutoInject { }

3. 在Application_Start()中初始化

 protected void Application_Start()
        {
            var builder = new ContainerBuilder();
//獲取IAutoInject的Type var baseType = typeof(IAutoInject); //獲取所有程式集 var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray(); //自動註冊介面 builder.RegisterAssemblyTypes(assemblies).Where
(b => b.GetInterfaces(). Any(c => c == baseType && b != baseType)).AsImplementedInterfaces(). InstancePerLifetimeScope(); //自動註冊控制器 builder.RegisterControllers(assemblies); var container = builder.Build(); DependencyResolver.SetResolver
(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }

注意: 獲取程式集的錯誤寫法(該寫法在回收程式池後會導致註冊資訊丟失): var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToArray();

4. 編寫測試程式碼

  public interface IStudent: IAutoInject
    {
        string Test();
    }
    public class Student : IStudent
    {
        public string Test()
        {
            return "ok";
        }
    }
        public class HomeController : Controller
    {
        private IStudent _student;

        public HomeController(IStudent student)
        {
            _student = student;
        }

        public ActionResult Index()
        {
            return Content(_student.Test());
        }
    }

訪問Home/index 即可看到ok成功輸出