微软的Unity使用

32 篇文章 0 订阅

你可以在http://unity.codeplex.com/ 下载到这个控件。我不知道百度上是否有它的中文解释。这里给大家贴出来codeplex上它的官方描述:

The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.

Unity addresses the issues faced by developers engaged in component-based software engineering. Modern business applications consist of custom business objects and components that perform specific or generic tasks within the application, in addition to components that individually address cross cutting concerns such as logging, authentication, authorization, caching, and exception handling.

The key to successfully building such applications is to achieve a decoupled or very loosely coupled design. Loosely coupled applications are more flexible and easier to maintain. They are also easier to test during development. You can mock up shims (lightweight mock implementations) of objects that have strong concrete dependencies; such as database connections, network connections, ERP connections, and rich user interface components.

Dependency injection is a prime technique for building loosely coupled applications. It provides ways to handle the dependencies between objects. For example, an object that processes customer information may depend on other objects that access the data store, validate the information, and check that the user is authorized to perform updates. Dependency injection techniques can ensure that the customer class correctly instantiates and populates all of these objects, especially where the dependencies may be abstract.

 

你可以在http://msdn.microsoft.com/zh-cn/library/dd203206(en-us).aspx 找到更多的关于Unity的资料。

下面我就以一个例子说明下它的使用:

1.先创建一个项目: UnityAspnetUsing:

 

 

2.你可以看到在MyObjects下面有连个interface: ILoggerIMyInterface两个接口,我这里以ILogger为例说明下,Unity的作用。

先看看ILogger的代码:

 

里面有个很简单的WriterMessages方法,返回结果是个string,下面创建两个使用这个接口的类:MyLoggerMyFastLogger

 

 

 

Ok,编译后,如果不使用Unity你需要先去实例化MyFastLogger来使用这个类的方法,WriteMessage,同样方法使用MyLogger。现在有了Unity,我们不再需要关心这个实例化的动作,需要做的如下:

 

使用IUnityContainer这个容器我们只需要去直接使用接口ILogger来使用某个方法。

如下:

 

这里的参数我们在config文件中定义出来了,如下:

 

所以可以使用standardloggersuperfastlogger来确定到底该调用哪个类中的方法:

 

Btn_GetLogger点击时通过loggerType的选择来确定调用standard或者是fastWriteMessage方法。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值