Microsoft实现的IOC DI之 Unity 、Service Locator、MEF
这几个工具的站点
Microsoft Unity http://unity.codeplex.com
Service Locator http://commonservicelocator.codeplex.com
MEF .net4.0内含,3.x前在codeplex上开源
Utility
The main reasons to use Unity (or any other IoC container) are if:
Ø You have dependencies between your objects .
Ø You need to manage the lifetime of an object .
Ø You want to manage dependencies at runtime, such as cache, constructors, and properties .
Ø You need to intercept the creation of an object .
Unity is a lightweight, extensible dependency injection container that supports interception, constructor injection, property injection, and method call injection. You can use Unity in a variety of different ways to help decouple the components of your applications, to maximize coherence in components, and to simplify design, implementation, testing, and administration of these applications.
Unity is a general-purpose container for use in any type of Microsoft® .NET Framework-based application. It provides all of the features commonly found in dependency injection mechanisms, including methods to register type mappings and object instances, resolve objects, manage object lifetimes, and inject dependent objects into the parameters of constructors and methods and as the value of properties of objects it resolves.
例子
[InjectionConstructor]
public Writer(ILogger logger)
{
this.logger = logger;
}
//Prepare the container
var container = new UnityContainer();
//We specify that the logger to be used is the FileLogger
container.RegisterType<ILogger, FileLogger>();
//and how to instantiate a new Writer
container.RegisterType<Writer>();
//Here Unity knows how to create the new constructor
var writer = container.Resolve<Writer>();
writer.Write("Some Text.");
通过UnityContainer实现注入
Service Locator
例子
/// <summary>
/// Utility to configure the container
/// </summary>
public sealed class UnityContainerConfigurator
{
/// <summary>
/// Configures this instance.
/// </summary>
/// <returns></returns>
public static IUnityContainer Configure()
{
var container = new UnityContainer()
.RegisterType<ILogger, FileLogger>()
.RegisterType<Writer>();
return container;
}
}
// create a new instance of Microsoft Unity container
var provider = new UnityServiceLocator(UnityContainerConfigurator.Configure());
// assign the container to the Service Locator provider
ServiceLocator.SetLocatorProvider(() => provider);
// resolve objects using the service locator
var writer = ServiceLocator.Current.GetInstance<Writer>();
writer.Write("Some Text.");
ServiceLocator的实现非常简单,而且代码也很少
MEF
The main reasons to use MEF are if:
Ø You need to implement external and reusable extensions in your client application, but you might have different implementations in different hosts .
Ø You need to auto-discover the available extensions at runtime .
Ø You need a more powerful and extensible framework than a normal Dependency Injection framework, and you want to get rid of the various boot-strapper and initializer objects .
Ø You need to implement extensibility and/or modularity in your components .
If your application doesn’t require any of the items in these lists, you probably should not implement the IoC pattern, and you might not need to use Unity and MEF .

例子
/// <summary>
/// Logger customized for MEF
/// </summary>
[Export(typeof(ILogger))]
public class MefLogger : ILogger
{
/// <summary>
/// Writes the log.
/// </summary>
/// <param name="message">The message.</param>
public void WriteLog(string message)
{
Console.WriteLine("String built from MEF: {0}.", message);
}
}
/// <summary>
/// Gets or sets the writer.
/// </summary>
/// <value>The writer.</value>
[Import]
public ILogger Writer { get; set; }
public void Run()
{
// first we build the catalog
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssemb
//create the container using the catalog
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
//use the resolved property
Writer.WriteLog("Mef message");
}
简单比较
Service Locator: 最简单的实现形式,对于比较简单的应用合适,本身的实现代码也很简单
Utility:复杂度中等,介于Service Locator和MEF之间
MEF:以一个完整的框架形式展现, .net 4内置支持,提供生命期等各种管理
Microsoft实现的IOC DI之 Unity 、Service Locator、MEF的更多相关文章
- 设计模式之初识IoC/DI(六)
本篇和大家一起学习IoC和DI即控制反转和依赖注入. 当然听上去这词语非常的专业,真不知道是怎么组出来的,看上去难归看上去难,但稍微理解一下也就这么回事了. 首先我们要明白IoC/DI干嘛用的,不然别 ...
- 服务定位器(Service Locator)
服务定位器(Service Locator) 跟DI容器类似,引入Service Locator目的也在于解耦.有许多成熟的设计模式也可用于解耦,但在Web应用上, Service Locator绝对 ...
- 使用Microsoft的IoC框架:Unity来对.NET应用进行解耦
1.IoC/DI简介 IoC 即 Inversion of Control,DI 即 Dependency Injection,前一个中文含义为控制反转,后一个译为依赖注入,可以理解成一种编程模式,详 ...
- Atitit。如何实现dip, di ,ioc ,Service Locator的区别于联系
Atitit.如何实现dip, di ,ioc ,Service Locator的区别于联系 1. Dip原则又来自于松耦合思想方向1 2. 要实现dip原则,有以下俩个模式1 3. Ioc和di的 ...
- 【IOC--Common Service Locator】不依赖于某个具体的IoC
你在你的应用程序应用IoC容器了吗,你是否希望不依赖于某个具体的IoC,微软的模式与实践团队在Codeplex上发布的Common Service Locator.Common Service Loc ...
- 关于依赖注入IOC/DI的感想
之前一直不明白依赖注入有什么好处,甚至觉得它是鸡肋,现在想想,当时真是可笑. 这个想法正如同说接口是没有用处一样. 当整个项目非常庞大,各个方法之间的调用非常复杂,那么,可以想象一下,假设说没有任何的 ...
- IoC/DI
From:http://jinnianshilongnian.iteye.com/blog/1471944 我对IoC/DI的理解 博客分类: spring杂谈 IoCDI IoC IoC: Inv ...
- asp.net core 四 IOC&DI Autofac
其实关于IOC,DI已经有了很多的文章,但是自己在使用中还是有很多困惑,而且相信自己使用下,印象还是会比较深刻的 关于这段时间一直在学习.net core,但是这篇文章是比较重要的,也是我自己觉得学习 ...
- 我对IoC/DI的理解
IoC IoC: Inversion of Control,控制反转, 控制权从应用程序转移到框架(如IoC容器),是框架共有特性 1.为什么需要IoC容器 1.1.应用程序主动控制对象的实例化及依赖 ...
随机推荐
- CSS 实现图片灰度效果
非原创-从网上收索出来的文章 CSS实现图片灰度效果就是通过CSS样式让彩色图片呈现为灰色,相当于把一张图像的颜色模式调整为灰度,CSS可以通过以下几种方法来实现灰度效果. 方式1. IE滤镜 img ...
- argunlar 1.0.0 【hello,world】
<!DOCTYPE html><html lang="en" ng-app><head> <meta charset="U ...
- pytorch之LSTM
from:http://pytorch-cn.readthedocs.io/zh/latest/package_references/torch-nn/#recurrent-layers class ...
- mount过程分析之一(基于3.16.3内核)【转】
转自:https://blog.csdn.net/zr_lang/article/details/39963253 一直想写有些关于文件系统的博文,但是由于近一年来实在太忙,所以没有时间写.前几日赶上 ...
- linux终端自定义设置
2014年1月4日 19:21:16 1. ls命令显示文件列表时不再花花绿绿 vi ~/.bashrc alias ls='ls -a --color=never' alias ll='ls -lh ...
- AudioEffect中文API
在Android2.3中增加了对音频混响的支持,这些API包含在android.media.audiofx包中. 一.概述 AudioEffect是android audio framework(an ...
- GPU下train 模型出现nan
When training on GPU, the error "Model diverged with loss = NaN" is often caused by a sotm ...
- https-配置使用HTTPS的ASP.NET Web应用
有关HTTPS.SSL以及SSL证书的工作原理,参见 <HTTPS-HTTPS原理> <HTTPS-SSL证书> <HTTPS-攻击实例与防御> 本文将演示如何在I ...
- Database Course Summary 001
0x01. 基本概念 SQL:Structured English Query Language 1. 数据 Data 数据(Data):描述事物的符号记录:数据内容是事物特性的反应或描述:数据是符号 ...
- SendMessage原理初探
今天跟踪一下SendMessage的实现. 用向导先创建一个Windows application. 向导生成了一个简单的窗口,如下. 在File菜单添加SendMessage,顺便添加一个PostM ...
