将用户类添加到所有演示者 [英] Adding user class to all presenters

查看:110
本文介绍了将用户类添加到所有演示者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对GIN有一种朦胧的理解,但是它对于注入演示者等有用。



我试图注入一个自制的User类到我所有的演示者,以获得当前登录的用户。



我已将@Inject添加到我的User类的构造函数中,并将User添加到了我的GIN模块...但除此之外,我完全失去了。我是否将它绑定到我的应用程序演示者(尝试过,但由于用户未扩展AppPresenter而出现错误)?作为一个单身?这是甚至正确的方式来传递这些数据吗?



我讨厌在这里发布这个(不是免费的家庭作业),但我找不到一个体面的教程/这个地方的例子。



非常感谢您提前。

解决方案

我看到两种可能性:


  • 注入源代码是 @提供方法 Provider 。但是,问题在于如何将当前登录的用户传递给这些方法,因为全局状态是一个禁忌。一个可能的解决方案是通过事件总线传递它,但在这一点上,它似乎有点击败DI的整个点(注入当前登录的用户是恕我直言,而不是DI的角色)。

  • 通过事件总线绕过用户。创建自定义事件,当用户登录/更改时触发,并且一些演示者监听该事件(毕竟,并非所有演示者都必须知道当前用户)。


我更喜欢和使用第二种方法 - 虽然DI很棒,但按照您描述的方式使用它似乎对我来说有点不好。我强烈建议查看 Guice文档 - 杜松子酒基本上Guice包装很好,可以和GWT一起工作,所以核心是一样的。对于其他指针如何有效地使用DI,并且通常编写可测试的代码,我强烈建议 Misko Hevery的博客以及编写可测试代码的指南(由Google内部使用)。


I have a hazy understanding of GIN, but have it working for injecting presenters, etc.

I'm trying to inject a self-made "User" class into all my presenters in order to get the currently logged-in user.

I've added @Inject to the constructor on my User class, and added User to my GIN module ... but apart from that, I'm totally lost. Do I bind it to my app presenter (tried that, but I get an error since User doesn't extend my AppPresenter)? As a singleton? Is this even the right way to get pass this data around?

I hate to post this here (not looking for free homework), but I can't find a decent tutorial/example on this anywhere else.

Much thanks in advance.

解决方案

I see two possibilities:

  • inject with the source being a @Provides method or a Provider. However, the problem is how to pass the currently logged in user to those methods, since global state is a no-no. A possible solution would be passing it via the event bus, but at this point it seems that it's kinda defeats the whole point of DI (injecting the currently logged in user is IMHO not the role of DI).
  • pass around the user via the event bus. Create a custom event that gets fired when the user logs in/changes, and some presenters listen for that event (after all, not all presenters have to know the current user).

I prefer and use the second approach - while DI is awesome, using it in the way you described seems kinda hackish to me. I strongly recommend checking out the Guice documentation - Gin is basically Guice wrapped nicely to work with GWT, so the core is the same. For some other pointers how to effectively use DI and, in general, write testable code, I strongly recommend Misko Hevery's blog and the guide to writing testable code he put up there (used internally by Google).

这篇关于将用户类添加到所有演示者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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