博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Microsoft实现的IOC DI之 Unity 、Service Locator、MEF
阅读量:5818 次
发布时间:2019-06-18

本文共 4022 字,大约阅读时间需要 13 分钟。

这几个工具的站点

Microsoft Unity  

Service Locator 

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://tjwdx.baihongyu.com/

你可能感兴趣的文章
推荐一个lucene的学习好去处,大神好博客
查看>>
七.redis 持久化
查看>>
Twitter Storm集群搭建小结
查看>>
jsoup使用样式class抓取数据时空格的处理
查看>>
使用truelicense实现用于JAVA工程license机制(包括license生成和验证)
查看>>
下载的.zip文件在Linux下unzip无法解压的解决方法
查看>>
认识 Iconfont 以及什么是 .eot、.woff、.ttf、.svg
查看>>
[译]Python设计模式:为了圆滑时尚的代码
查看>>
Corba开发总结(一)---JacORB的安装与编译
查看>>
13、Eternal框架-工程项目管理系统-登录
查看>>
Linux C语言 头文件搜索路径
查看>>
火狐 bootstrap pre 不换行
查看>>
iOS 知识-常用小技巧大杂烩
查看>>
easyui datebox 只读设置
查看>>
Drupal7全局变量的使用
查看>>
《Linux 系列》- 常用命令- 文件操作命令
查看>>
android studio运行卡慢的解决方案
查看>>
开始发博文啦
查看>>
Android当道,不加密的APP必死
查看>>
Excel 2003文档的密码忘了怎么办
查看>>