首頁 C# DI Container Use Autofac
文章
Cancel

C# DI Container Use Autofac

使用以下套件
Desktop View

1
NuGet\Install-Package Autofac -Version 6.3.0

Code Example

使用下來,覺得在使用MVC的時候效果最明顯
Desktop View

Autofac

1
NuGet\Install-Package Autofac -Version 6.3.0

Autofac.Mvc5

1
NuGet\Install-Package Autofac.Mvc5 -Version 6.1.0

建立要使用DI的Class與Interface

1
2
3
4
5
6
7
8
9
10
11
12
  public interface ILogger
  {
      void Log(string msg);
  }
  public class Logger : ILogger
  {
    
      public void Log(string msg)
      {
          Console.WriteLine("LOG:" + msg);
      }
  }

建立用來實現DI的Class,例如AutofacConfig.cs
Desktop View AutofacConfig.cs 內部長這樣

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using Autofac;
using Autofac.Integration.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace AutofacMVC.App_Start
{
    public  class AutofacConfig
    {
        public static void Run()
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<Logger>().As<ILogger>();
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }

}

在Global.asax 添加Method
Desktop View

最後在Controoler正在使用DI注入例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using AutofacMVC.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AutofacMVC.Controllers
{
    public class HomeController : Controller
    {
        protected ILogger Logger;  
        public HomeController(ILogger logger)
        {
            Logger= logger;
         
        }
        public ActionResult Index()
        {
            return View();
        }
    }
}

可以搭配的技術

本文由作者按照 CC BY 4.0 進行授權