Auto fac的介紹 20131018

11

Click here to load reader

Transcript of Auto fac的介紹 20131018

Page 1: Auto fac的介紹 20131018

AutoFac 的介紹Bryan Lin

2013/10/18

Page 2: Auto fac的介紹 20131018

Agenda

AutoFac 是什麼? Why AutoFac ?

How to use AutoFac ?

Q & A

Page 3: Auto fac的介紹 20131018

AutoFac 是什麼?

一種可以讓你的專案使用 Inversion of Controll (IoC) 的 Framework

使用簡單的方式來實作 IoC ,讓程式碼看起來更簡潔 有關 dependency injection/inversion of control 的說明,可至下列網站參考:

http://martinfowler.com/articles/injection.html

Page 4: Auto fac的介紹 20131018

Why AutoFac ?

讓程式的測試較為容易進行 保留程式的彈性 在眾多 IoC Framework 中, AutoFac 是文件較多,比較容易學習的

Page 5: Auto fac的介紹 20131018

How to use AutoFac ?

已經有寫好的程式碼如下:

Page 6: Auto fac的介紹 20131018

How to use AutoFac ?

安裝 AutoFac 的 NuGet 包

Page 7: Auto fac的介紹 20131018

How to use AutoFac ?

使用方式: 要定義類別的 Interface

public class SomeType : IService

{

}

Page 8: Auto fac的介紹 20131018

How to use AutoFac ?

建立 ContainerBuilder 來註冊 IoC 的類別

// Create your builder.

var builder = new ContainerBuilder();

// Usually you're only interested in exposing the type

// via its interface:

builder.RegisterType<SomeType>().As<IService>();

// However, if you want BOTH services (not as common)

// you can say so:

builder.RegisterType<SomeType>().AsSelf().As<IService>();

Page 9: Auto fac的介紹 20131018

How to use AutoFac ?

以我們剛才的程式碼,我們可以這樣使用:

Page 10: Auto fac的介紹 20131018

How to use AutoFac ?

接著實作 WriteDate 這個方法

Page 11: Auto fac的介紹 20131018

Q & A