WPF /棱镜:什么是UNITY集装箱? [英] WPF/Prism: What is a UNITY Container?

查看:255
本文介绍了WPF /棱镜:什么是UNITY集装箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我一个6岁的孩子给我是否有人可以解释团结容器的概念?它是如何工作以及它有什么作用?

Can someone please explain to me the notion of a Unity Container like I'm a 6 year old kid? How does it work and what does it do?

推荐答案

这是背景的技术性描述,我希望你还是找它是有用的。

This is a more technical description of the background, I hope you still find it useful.

一般的说,它是DI(依赖注入)容器中。

Generally put, it is a DI (dependency injection) container.

考虑下面的类

public class Sample
{
  Service a;

  public Sample()
  {
    a = new Service();
  }
}



与的问题是,它初始化它自己的版本服务,使得它很难对代码变更调整(比如,如果你想交换服务有一些不同的)。 。此外,它使测试难以

The problem with that is that it initializes its own version of Service, making it very hard to adjust for code changes (ie. if you want to exchange Service with something different). Also it makes testing difficult.

要解决,实际上并不自行创建它,但是从外面得到它:

To resolve that, don't actually create it yourself, but get it from the outside:

public class Sample
{
  Service a;

  public Sample(Service aService)
  {
    a = aService;
  }
}

现在你已经采取了创作远离类,你只需把它放在那里从外面,增加了可测试性和可维护性。不过,你还是对类服务的依赖。你是不是在特定的类很感兴趣,但在行为它提供了 - 所以您在接口出来的

Now you have taken the creation away from the class you can just put it in there from the outside, increasing testability and maintainability. However, you still have a dependency on the class Service. You aren't really interested in that specific class, but in the behaviour it offers - so you make in interface out of it.

public class Sample
{
  IService a;

  public Sample(IService aService)
  {
    a = aService;
  }
}

现在,你可以用任何你喜欢的更换服务。例如,你有一个类使用服务从服务器获取数据。现在,你只需要测试数据分析,而不是数据抓取服务 - 只需创建实现接口的类,提供静态数据 - 完成

Now, you can replace the service with anything you like. For example, you have a class getting data from a server using a service. Now, you want to test only the data parsing and not the data fetching service - just create a class implementing the interface, serving static data - done!

现在,统一配备发挥作用。此刻,你必须自己解决的依赖关系。什么团结确实很简单 - 它需要有dependendencies所有类和解决这些 - 所以你可以致电(伪代码,我不知道团结):

Now, Unity comes into play. At the moment, you have to resolve the dependencies yourself. What unity does is simple - it takes all classes that have dependendencies and resolves those - so you can just call (pseudocode, I don't know unity):

UnityContainer uc = new UnityContainer();
var a = uc.GetService<IService>();

和它可以让你随手可用类。

And it gets you the readily useable class.

我们有什么由achivied?

What do we have achivied by that?


  • 代码更易于维护,因为你不依赖于特定类型的
  • 代码的可测试性

  • 的应用程序易于扩展

作为总结:它有助于创造更好的应用程序更快

As a summary: it helps creating better applications faster.

这篇关于WPF /棱镜:什么是UNITY集装箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆