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内置支持,提供生命期等各种管理

实例代码: http://cid-56b433ad3d1871e3.office.live.com/self.aspx/.Public/Ioc%5E_Di.rar

时间: 2024-08-02 01:30:10

Microsoft实现的IOC DI之 Unity 、Service Locator、MEF的相关文章

如何理解IoC/DI

IoC:Inversion of Control,控制反转DI:Dependency Injection,依赖注入 要理解上面两个概念,就必须搞清楚如下的问题: 参与者都有谁?依赖:谁依赖于谁?为什么需要依赖?注入:谁注入于谁?到底注入什么?控制反转:谁控制谁?控制什么?为什么叫反转(有反转就应该有正转了)?依赖注入和控制反转是同一概念吗? 下面就来简要地回答一下上述问题,把这些问题搞明白了,也就明白IoC/DI了.(1)参与者都有谁:一般有三方参与者,一个是某个对象:另一个是IoC/DI容器(

IOC DI

IoC:Inversion of Control,控制反转DI:Dependency Injection,依赖注入 要理解上面两个概念,就必须搞清楚如下的问题: 参与者都有谁?依赖:谁依赖于谁?为什么需要依赖?注入:谁注入于谁?到底注入什么?控制反转:谁控制谁?控制什么?为什么叫反转(有反转就应该有正转了)?依赖注入和控制反转是同一概念吗? 下面就来简要地回答一下上述问题,把这些问题搞明白了,也就明白IoC/DI了.(1)参与者都有谁:一般有三方参与者,一个是某个对象:另一个是IoC/DI容器(

Common Service Locator library

你在你的应用程序应用IoC容器了吗,你是否希望不依赖于某个具体的IoC,微软的模式与实践团队在Codeplex上发布的Common Service Locator.Common Service Locator 类库包含应用程序和框架开发者引用Service location共享的接口.这个类库提供了在IOC容器和Service locators之上抽象.使用这个类库允许一个应用程序在没有强引用依赖下间接的访问的能力.它所定义的接口非常简单: namespace Microsoft.Practic

使用Websharp Service Locator简化分布式系统开发

web|分布式 使用Websharp Service Locator 简化分布式系统开发 什么是Websharp Service Locator对于多层的应用系统来说,我们通常把它们划分成客户端.应用服务层和数据库.在应用服务层,我们需要考虑至少两个方面的问题: ü 如何实现业务逻辑 ü 如何向客户端提供服务. 我们可能使用多种技术来实现服务的提供:Webservice..Net Remoting.甚至EJB等.如此多的实现技术,带来的很大的灵活性,但同时也带来了问题,其中一个就是,有多少种服务

使用Microsoft Robotics Studio实现和扩展一个Service Contract

这篇文章描述了使用三种方法来实现或扩展一个通用服务协议(generic service contract),其中 包括实现一个通用服务协议.扩展一个服务协议以及多头服务(Multi-Headed Service),这个实例中使 用的通用的服务协议是在Service Tutorial 8 (C#) - Generic Service Declaration.所创建的. 这个实例由C#实现,可以在下面的目录中找到这个项目: Samples"ServiceTutorials"Tutorial

对DIP IoC DI的理解与运用

DIP,IoC,DI基本概念 依赖倒置原则(DIP,Dependency Inverse Principle):强调系统的"高层组件"不应当依赖于"底层组件",并且不论是"高层组件"还是"底层组件"都应当依赖于抽象.抽象不应当依赖于实现,实现应当依赖于抽象. 依赖(Dependency):组件A如果:①持有B的引用,②调用B的方法,③创建(new)B,则A对B产生依赖. 控制(Control):A依赖B,则B拥有"控

ASP.NET MVC3 Service Location

介绍 ASP.NET MVC3 的一个重要的新特性就是允许注册一个服务点 Service Location,然后在框架中使用的能力.以前版本的 MVC 已经提供了 Service Location 和依赖注入的机会,在 MVC3 中,我们正式提供了这种能力,并且为开发者开放了多种使用的机会. 总体策略 关于 Service Location 的最重要的部分就是它是可选的,这意味着如果你对 Service Location 不感兴趣,那么,你不需要被强制使用,你总是可以在不使用 Service L

ASP“.NET研究”.NET MVC3 Service Location

介绍 ASP.NET MVC3 的一个重要的新特性就是允许注册一个服务点 Service Location,然后在框架中使用的能力.以前版本的 MVC 已经提供了 Service Location 和依赖注入的机会,在 MVC3 中,我们正式提供了这种能力,并且为开发者开放了多种使用的机会. 总体策略 关于 Service Location 的最重要的部分就是它是可选的,这意味着如果你对 Service Location 不感兴趣,那么,你不需要被强制使用,你总是可以在不使用 Service L

一起谈.NET技术,ASP.NET MVC3 Service Location

介绍 ASP.NET MVC3 的一个重要的新特性就是允许注册一个服务点 Service Location,然后在框架中使用的能力.以前版本的 MVC 已经提供了 Service Location 和依赖注入的机会,在 MVC3 中,我们正式提供了这种能力,并且为开发者开放了多种使用的机会. 总体策略 关于 Service Location 的最重要的部分就是它是可选的,这意味着如果你对 Service Location 不感兴趣,那么,你不需要被强制使用,你总是可以在不使用 Service L