2014年6月4日 星期三

Autofac 一種IOC容器

接續之前提到的IOC 控制反轉 & DI 依賴注入Repostitory Pattern,在Controller中提供了Repository介面的建構式,接下來就來介紹如何在網站啟動的時後,利用IOC容器把介面注入

首先透過NuGet安裝Autofac套件

因為是MVC專案,所以還要再裝一個MVC整合套件

依照慣例在App_Start資料夾下新增一個AutofacConfig
namespace WebApplication1
{
    using Autofac;
    using Autofac.Integration.Mvc;
    using System.Reflection;
    using System.Web.Mvc;

    public class AutofacConfig
    {
        public static void RegisterDependies()
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .Where(x => x.Namespace.EndsWith("Repositories"))
                .AsImplementedInterfaces();
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}

在Global的Application_Start事件中啟用Autofac
namespace WebApplication1
{
    using System.Web.Mvc;
    using System.Web.Routing;

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            AutofacConfig.RegisterDependies();
        }
    }
}