惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Help Net Security
Help Net Security
G
Google Developers Blog
雷峰网
雷峰网
WordPress大学
WordPress大学
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Engineering at Meta
Engineering at Meta
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
AWS News Blog
AWS News Blog
F
Full Disclosure
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Exploit Database - CXSecurity.com
J
Java Code Geeks
U
Unit 42
C
Cyber Attacks, Cyber Crime and Cyber Security
V
V2EX
C
Cisco Blogs
博客园 - 司徒正美
Project Zero
Project Zero
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
Blog — PlanetScale
Blog — PlanetScale
Scott Helme
Scott Helme
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog
S
Securelist
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
G
GRAHAM CLULEY
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyberwarzone
Cyberwarzone
MongoDB | Blog
MongoDB | Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
T
Threatpost
Recorded Future
Recorded Future
C
CXSECURITY Database RSS Feed - CXSecurity.com
宝玉的分享
宝玉的分享
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
The Register - Security
The Register - Security
S
Security Archives - TechRepublic
博客园 - Franky
N
News | PayPal Newsroom
Simon Willison's Weblog
Simon Willison's Weblog
S
SegmentFault 最新的问题
W
WeLiveSecurity
A
Arctic Wolf
B
Blog

博客园 - 黃偉榮

Web Project的檔案共用小技巧 UTF8Encoding與BOM Temporary Post Used For Theme Detection (d4b0aefa-c88e-4957-bba7-b367d1bfa042 - 3bfe001a-32de-4114-a6b4-4005b770f6d7) 寫CodedUI時如何尋找控制項的小技巧 Visual Studio 2010 Feature Packs 2之Silverlight自動化測試 Moles - Isolation framework for .NET(假.Net)介紹 [小技巧]Entity Framework強型別Include C#仿Oracle Decode,將ValueType對應成String - 黃偉榮 - 博客园 Visual Studio 單元測試的3種Initialize與Cleanup jQuery套件-檢查頁面的欄位是否有變更 用EventLogReader查詢特殊EventLog jQuery自製Plugin-Bind事件函式時檢查有沒有Bind過 ASP.NET MVC TempData使用心得 Visual Stuiod 自訂檔案比較合并工具 [小技巧]自動化測試時NLog的訊息輸出到測試結果中 小技巧:專案切換32與64位元組件 Linq小技巧:日期處理 Unit Test小技巧 : DateTime的Stub 解決TFS Build Asp.Net Mvc開啟MvcBuildViews後無法載入組件問題
IoC的中繼器:CommonServiceLocator
黃偉榮 · 2011-01-30 · via 博客园 - 黃偉榮

IoC(控制反轉)是時下很流行的設計模式,它可以大大的簡少程式之間的相依性,有點像工廠模式,在Class中操作的都是Interface,而Interface與Class的對應與建立實例都是由IoC Framework處理,光是在.Net Framework下的IoC Framework就有近10套,每套都有各自的優缺點,呼叫方式也略有不同,切換IoC Framework是非常麻煩的,或是開發組件(Assembly),組件也是使用IoC,但是又不能限制使用端用特定款IoC Framework,這時候可以考慮使用IoC的中繼器:CommonServiceLocator來解決這個問題。

NOTE:

IoC的文章很多人寫,而且也寫的非常完整與詳細,小弟就不在這裡多述,各位可以參考以下文章:

In 91 : [Software Architecture]IoC and DI

黃忠成 :  Inside ObjectBuilder Part1

什麼是CommonServiceLocator

service locator 2

官方網址:http://commonservicelocator.codeplex.com/

CommonServiceLocator是放在Codeplex中由Microsoft patterns & practices團隊所設計的小組件,它很輕所有的Code才一百多行,它主要的定義一些Interface,讓我們的程式是呼叫CommonServiceLocator,透過CommonServiceLocator去呼叫IoC Framework,如同中繼器一般,使我們的程式不會綁死於一同IoC Framework,而且有提供主流的IoC Framework用的Provider(就算未提供也可以自己寫),支援非常的廣泛。

支援的IoC Framework如下:

  • Castle Windsor
  • Spring .NET
  • Unity
  • StructureMap
  • Autofac
  • MEF
  • LinFu

使用方式:

//泛型
//第一個Method,也是最常用的Method
ICreditCardService instance = ServiceLocator.Current.GetInstance<ICreditCardService>();

//第二個多載Method,因為一個Interface,所能有很多個Class實作,如果有設定Key,可以用Key指定要實例的Type
ICreditCardService instance = ServiceLocator.Current.GetInstance<ICreditCardService>("中國信託");


//非泛型的
ICreditCardService instance = (ICreditCardService)ServiceLocator.Current.GetInstance(typeof(ICreditCardService));

ICreditCardService instance = (ICreditCardService)ServiceLocator.Current.GetInstance(typeof(ICreditCardService), "中國信託");


//從System.IServiceProvider繼承來的,不過看了幾個Provider,GetService都只是呼叫GetInstance,所以沒什麼不同
ICreditCardService instance = (ICreditCardService)ServiceLocator.Current.GetService(typeof(ICreditCardService));

註冊Provider

//先註冊IoC的東西
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<OrderService>().As<IOrderService>();
builder.RegisterType<中國信託CreditCardService>().Named<ICreditCardService>("中國信託");
builder.RegisterType<台北富邦CreditCardService>().Named<ICreditCardService>("台北富邦");

//最後在設定Provider
ServiceLocator.SetLocatorProvider(() => new MyServiceLocator(builder)); 

這裡介紹幾個常見的IoC設定方式,詳情請看官方網站的說明。

Autofac的設定

Autofac網站下載AutofacContrib,加入參考AutofacContrib.CommonServiceLocator.dll

ContainerBuilder builder = new ContainerBuilder();
var container = builder.Build();
ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(container));

Spring .NET的設定

下載:CommonServiceLocator.SpringAdapter.zip,加入參考CommonServiceLocator.SpringAdapter.dll

DefaultListableObjectFactory objectFactory = new DefaultListableObjectFactory(false);
objectFactory.RegisterSingleton(typeof(SimpleLogger).FullName, new SimpleLogger());
objectFactory.RegisterSingleton(typeof(AdvancedLogger).FullName, new AdvancedLogger());

ServiceLocator.SetLocatorProvider(() => new SpringServiceLocatorAdapter(objectFactory));

Unity的設定

下載:CommonServiceLocator.UnityAdapter.zip,加入參考Microsoft.Practices.Unity.ServiceLocatorAdapter.dll

IUnityContainer container = new UnityContainer() 
    .RegisterType<ILogger, AdvancedLogger>() 
    .RegisterType<ILogger, SimpleLogger>(typeof (SimpleLogger).FullName) 
    .RegisterType<ILogger, AdvancedLogger>(typeof (AdvancedLogger).FullName);

ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container)); 
return new UnityServiceLocator(container);

StructureMap的設定

下載:CommonServiceLocator.StructureMapAdapter.zip,加入參考StructureMapAdapter.dll

Registry registry = new Registry();
registry.ForRequestedType<ILogger>().TheDefaultIsConcreteType<AdvancedLogger>();
registry.AddInstanceOf<ILogger>(new SimpleLogger()).WithName(typeof(SimpleLogger).FullName);
registry.AddInstanceOf<ILogger>(new AdvancedLogger()).WithName(typeof(AdvancedLogger).FullName);
IContainer container = new Container(registry);

ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(container));