Autofac 簡單範例

Autofac 應用在MVC 和 WebApi

開始前要先去Nuget 安裝
Autofac  (其實下面兩個會相依安裝)
Autofac.Mvc5
Autofac.WebApi2   (不是WebApi)
 

建立Autofac有四個步驟

  1. 建立容器Builder
  2. 註冊服務 (讓Autofac認識)
  3. 由Builder建立容器
  4. 把容器設定給DependencyResolver
public static class AutofacConfig
{
    public static void Run()
    {
        // === 1. 建立容器 ===
        var builder = new ContainerBuilder();

        // === 2. 註冊服務 ===
        //取得目前執行App的Assembly
        Assembly assembly = Assembly.GetExecutingAssembly();

        //如果要註冊的的物件不再同一個Assembly則用
        //Assembly assembly = typeof(OtherService).Assembly;

        /*下面有幾種常用註冊方法*/
        //A.直接註冊某個物件
        builder.RegisterType<MyService>().As<IMyService>();  //表示註冊MyService這個Class並且為IMyService這個物件的實作

        //B.註冊所有名稱為Service結尾的物件
        builder.RegisterAssemblyTypes(assembly)
            .Where(x => x.Name.EndsWith("Service", StringComparison.Ordinal))
            .AsImplementedInterfaces();

        //C.註冊所有父類別為BaseMethod的物件
        builder.RegisterAssemblyTypes(assembly)
            .Where(x => x.BaseType == typeof(BaseMethod)).AsImplementedInterfaces();

        //D.註冊實作某個介面的物件
        builder.RegisterAssemblyTypes(assembly)
            .Where(x=>x.GetInterfaces().Contains(typeof(ICommonMethod))).AsImplementedInterfaces();

        //***重要*** 註冊Controller和ApiController
        builder.RegisterControllers(assembly);
        builder.RegisterApiControllers(assembly);

        // === 3. 由Builder建立容器 ===
        var container = builder.Build();


        // === 4. 把容器設定給DependencyResolver ===
        var resolverApi = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolverApi;
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
}

最後在 App啟動點Global呼叫啟用Autofac

public class WebApiApplication : System.Web.HttpApplication
{
    public void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        //啟用Autofac
        AutofacConfig.Run();
    }
}

這時候我們就可以在WebApi Controller和MVC Controller中自動DI那個物件

public class HomeController : Controller
{
    private readonly IMyService myService;
    private readonly ICommonMethod commonMethod;
    public HomeController(IMyService myService,ICommonMethod commonMethod)
    {
        this.myService= myService;
        this.commonMethod = commonMethod;
    }

    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";
        var q=  commonMethod.swim();
        return View(myService.OperationNumber(1,2));
    }
}
public class TestController : ApiController
{
    private IMyService ms;
    public TestController(IMyService service)
    {
        ms = service;
    }

    [HttpGet]
    public int Test()
    {
        return ms.OperationNumber(9, 8);
    }
}