hadashiA / VContainer

The extra fast, minimum code size, GC-free DI (Dependency Injection) library running on Unity Game Engine.
https://vcontainer.hadashikick.jp
MIT License
1.89k stars 165 forks source link

[Question] Injection on ScriptableObject #562

Closed ATHellboy closed 10 months ago

ATHellboy commented 11 months ago

Hey guys, I have another question and I had to drop it here.

I have a Player gameObject that Instantiate a Character prefab which contains LifetimeScope. Instantiated Character gameObject has CharacterController facade which Instantiate a few ScriptableObjects. These ScriptableObjects have a Constructor method (Method Injection). One of the classes which should be injected is already registered by Character LifetimeScope.

The issue is, it can't find registration of that type. My first guess is, I should specify the LifetimeScope parent which is Character LifetimeScope for these ScriptableObjects but no idea how and even I don't know if it is a right guess.

Also it is a reporuction project to demonstrate the issue: VContainerScriptableObjectReproduction.zip

ATHellboy commented 10 months ago

So I just found out i can achieve that by using this:

[Inject]
public void Construct(IObjectResolver container)
{
    _container = container;
}

void Start()
{
    var powerup = UnityEngine.Object.Instantiate(_powerup);
    _container.Inject(powerup);
}

Now I want to know if it is a right approach ? Is there any better and clearer way to achieve that ? Also Awake on ScriptableObject called before the constructor and nothing comes to my mind to fix that.

Reproduction project for fixing the issue I had: VContainerScriptableObjectReproduction.zip

hadashiA commented 10 months ago

Hmm, I did not suppose to instantiate ScriptableObjects.

Like you said, this code seems to serve the purpose.

var powerup = UnityEngine.Object.Instantiate(_powerup);
_container.Inject(powerup);

In fact, container.Instantiate(...) does something similar to this.