匕首:如果我每次都*想要*一个新实例怎么办? [英] Dagger: What if I *WANT* a new instance every time?
问题描述
有趣的是,很难找到答案。
Interesting how difficult this answer is to find.
我已经使用Dagger-Android已有一段时间了,并设置了我的整个依赖关系图。我正在使用范围,限定词以及所有这些好东西。我已经不再是Dagger的新手了,不过可以说我已经在我的Android设置中以非常标准的方式使用它了,一切都进行得很好。
I've been using Dagger - Android for a while now and have my entire dependency graph set up. I'm using scopes, qualifiers, all that good stuff. I'm not a Dagger newbie anymore, but suffice to say I've been using it in a pretty standard way in my Android setup and everything has been going great.
第一次,我意识到我想手动地在自己的图形中请求某个类的新实例,并且我希望每次都是新实例。
For the first time, I'm realizing that I'd like to request new instances of a certain class in my graph myself, manually, and I want it to be a new instance every time.
执行此操作的最佳方法是什么?我想知道是否有一种方法可以利用非@ Singleton /非作用域提供程序并自己调用某种 create()
方法,或者是否最好创建自己创建一个工厂,并让该工厂成为单例/作用域实例,并在需要时使用我的工厂来获取新实例? [我应该提一下,此类肯定没有具有空的构造函数,因此需要在注入图中定义的其他类的注入实例。
What's the best way to go about doing that? I'm wondering if there's a way to leverage a non-@Singleton/non-scoped provider and call some sort of create()
method myself, or if it's best to create a factory myself and make that factory a singleton/scoped instance and use my factory to get the new instance(s) when I need them? [I should mention this class will definitely not have an empty constructor so will need injected instances of other classes defined in my injection graph.]
(此外,如果答案是在Android上下文中,这可能会最大程度地帮助您;例如,我在ViewModel中,并且需要在我的一个模块中定义的某个类的新实例。)
(Also, it would probably help the most if answers were in the context of Android; i.e. I'm in, say, a ViewModel and need a new instance of some class defined in one of my Modules.)
推荐答案
只要您不限制依赖项,Dagger就会为您提供一个新实例。
Dagger will provide you a new instance as long as you don't scope the dependency.
要手动获取依赖项的新实例,可以注入它的 Provider
并使用其 get()
方法,每次调用它都会为您提供一个新实例。
To get a new instance of a dependency manually, you can inject Provider
of it instead and use its get()
method, it'll give you a new instance every time you call it.
模块部分并没有真正改变:
Module part doesn't really change:
@Module
class AppModule {
@Provides
fun provideSomeObject(): SomeObject = SomeObject()
}
在您的班上
class SomeClass {
// We don't inject the object anymore
// @Inject lateinit var myObject : SomeObject
// We'll inject it's provider
@Inject lateinit var myObject : Provider<SomeObject>
fun someMethod(){
// Here, instance1 and instance2 are NOT same objects
val instance1 = myObject.get()
val instance2 = myObject.get()
}
}
您可以阅读更多此处。
这篇关于匕首:如果我每次都*想要*一个新实例怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!