gustavopsantos / Reflex

Minimal dependency injection framework for Unity
MIT License
730 stars 51 forks source link

Injected attributes in base class do not work in derived class if private #51

Closed 3vilrabbit closed 6 months ago

3vilrabbit commented 6 months ago

Describe the bug Injected attributes in base class do not work in derived class if private. They do work if defined as protected or public.

To Reproduce Steps to reproduce the behavior:

  1. Create two monobehaviour class: ClassA and ClassB, ClassB inherit from base class ClassA.
  2. Create two services (not monobehaviour) ServiceA and ServiceB with a simple method Execute which just print a string to console.
  3. In ClassA define [Inject] private ServiceA _serviceA as private member field, in Start() methods just call _serviceA.Execute() method
  4. In Class B define [Inject] private ServiceB _serviceB as private member field, in Start() methods just call base.Start() and _serviceB.Execute() method
  5. Create Scene scope installer for both services.

Expected behaviour Both string should be printed in the console but only the service B works. If _serviceA is defined as [Inject] protected ServiceA _serviceA or [Inject] public ServiceA _serviceA both strings are printed.

public class ClassA : MonoBehaviour
{
    [Inject] private ServiceA _serviceA;

    protected virtual void Start()
    {
        if (_serviceA != null)
        {
            _serviceA?.Execute();
        }
        else
        {
            Debug.Log("service A is not injected");
        }
    }
}

public class ClassB : ClassA
{
    [Inject] private ServiceB _serviceB;

    protected override void Start()
    {
        base.Start();
        _serviceB?.Execute();
    }
}

public class ServiceA
{
    public void Execute()
    {
        Debug.Log("I am service A");
    }
}

public class ServiceB
{
    public void Execute()
    {
        Debug.Log("I am service B");
    }
}

public class DependencyInstaller : MonoBehaviour, IInstaller
{
    public void InstallBindings(ContainerBuilder containerBuilder)
    {
        containerBuilder.AddSingleton(new ServiceA());
        containerBuilder.AddSingleton(new ServiceB());
    }
}
gustavopsantos commented 6 months ago

@3vilrabbit Thanks for reporting this issue, I fixed it in latest release, see https://github.com/gustavopsantos/Reflex/releases/tag/8.1.1 ;)