Inheritance and Dependencies

  9. Problems & Solutions No Comments

Problem

You have a base class that depends on some services.

You want to create a class that derives from that base class, which depends on some additional services on top of the ones that the base class does.

class Base : MonoBehaviour<A, B>
{
    // The base class depends on some services
    A a;
    B b;

    protected override void Init(A a, B b)
    {
        this.a = a;
        this.b = b;
    }
}

class Derived : Base
{
    // A derived type depends on some additional services
    C c;
    D d;
}

Since the Derived class must derive from Base, it can not simultanously derive from MonoBehaviour<A, B, C, D>.

How can Derived be defined in such a way that:

  1. all four dependencies can be provided to it from the outside,
  2. and it will be able to acquire the dependencies automatically at the beginning of the Awake event?

Solution

To make it possible to inject all the objects that your derived class and its base class depend on, implement the IInitializable<T…> interface, and list the types of all their combined dependencies as generic type arguments of the interface.

You will also need to override the bool Init(Context) method, to make it acquire all the combined dependencies at the beginning of the Awake event, instead of just the ones that the base class depends on.

public class Derived : Base, IInitializable<A, B, C, D>
{
    C c;
    D d;

    // Implement Init(A, B, C, D) to be able to receive four Init arguments
    public void Init(A a, B b, C c, D d)
    {
        // Init the base type
        Init(a, b);

        // Init the derived type
        this.c = c;
        this.d = d;
    }

     // Override Init(Context) to acquire the all four Init arguments at the beginning of the Awake event.
     protected override bool Init(Context context) => InitArgs.TryGet<A, B, C, D>(this);
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *