[C#][ASP.NET MVC5][Autofac] DI Framework - AutofacConfig.cs

之前嘗試很多次都失敗,這次終於成功註冊Controller、Service與Repository了,來記錄一下設定檔。

  • 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
24
25
26
27
28
29
30
31
32
33
34
35
36
37

/// <summary>
/// DI設定檔
/// </summary>
public class AutofacConfig
{
/// <summary>
/// 註冊DI注入物件資料
/// </summary>
public static void Register()
{
// 容器建立者
ContainerBuilder builder = new ContainerBuilder();

// 註冊Controllers
builder.RegisterControllers(Assembly.GetExecutingAssembly());

// 註冊Service
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.Name.EndsWith("Service"))
.AsSelf();

// 註冊Repository
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.Name.EndsWith("Repository"))
.AsSelf();

// 建立容器
IContainer container = builder.Build();

// 解析容器內的型別
AutofacDependencyResolver resolver = new AutofacDependencyResolver(container);

// 建立相依解析器
DependencyResolver.SetResolver(resolver);
}
}
  • Global.asax
1
2
3
4
5
6

protected void Application_Start()
{
//加入這行
AutofacConfig.Register();
}