如何使用 AngularDart 基于类型和名称进行依赖注入? [英] How can I Dependency Inject based on type and name, with AngularDart?

查看:19
本文介绍了如何使用 AngularDart 基于类型和名称进行依赖注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个服务,每个服务都使用一个不同的 WebSocket 作为构造函数参数.我想使用 AngularDart 的依赖注入来传入 WebSocket 连接,但我不能单独依赖类型(因为我有两个 WebSocket).

I have two services, each of which takes a different WebSocket as a constructor parameter. I'd like to use AngularDart's dependency injection to pass in the WebSocket connection, but I can't rely on types alone (as I have two WebSockets).

如何注释或指定每个服务应该使用哪个特定的 WebSocket 连接?

How can I annotate or specify which specific WebSocket connection should to each service?

假设我有:

class ServiceOne {
  WebSocket socketOne;
  ServiceOne(this.socketOne);
}

class ServiceTwo {
  WebSocket socketTwo; // different connection
  ServiceTwo(this.socketTwo);
}

谢谢!

推荐答案

如果你看一下 GUICE,这个问题就很好理解了.(https://code.google.com/p/google-guice/)问题是,当您检索实例时,您需要某种Key(这就是 GUICE 所称的).有几种方法可以获得Key.

This problem is well understood if you look at GUICE. (https://code.google.com/p/google-guice/) The issue is that when you are retrieving an instance you need to have some sort of Key (this is what GUICE calls it). There are several ways you can get a Key.

在 AngularJS 中,我们简化了这个问题,并说参数名称是 Key.由于 JS 在源代码中没有类型,这确实是我们对 Key 的唯一选择.

In AngularJS, we simplified the issue and said that the parameter name is the Key. Since JS has no types in source code, that was really the only choice we had for a Key.

在 AngualDart 中,我们对其进行了改进,并使用 Type 作为 Key.这样做的好处是参数名称无关紧要.但它产生了一个问题,即您只能注入每个 Type 中的一个.对于自定义类型,这没什么大不了的,但是只有一个 String 配置类型就成了一个问题.

In AngualDart we have improved it and used the Type as the Key. This has the benefit that the parameter name is irrelevant. But it creates an issue that you can only ever inject one of each Type. For custom types it is not a big deal, but to have only one String configuration type becomes an issue.

这个问题的解决方案是在类型之上添加注解.所以Annotation + Type 就是Key.下面是可能的样子:

The solution to this problem is to have annotations on top of types. So that Annotation + Type is the Key. Here is what that may look like:

注意:这些都不存在,只是一个建议,如何解决.

class MyClass {
  MyClass(@Url String url, @Secret String secret) { ... }
}

Module module = new Module();
module.value(key(String, [Url]), 'http://server.com/...');
module.value(key(String, [Secret]), 'A89B42C');

请求:由于这些还没有实现,如果您热衷于帮助 AngularDart 并希望帮助实现这一目标,请与我联系.

这篇关于如何使用 AngularDart 基于类型和名称进行依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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