Dependency Injection

DOTSNET comes with dependency injection for all systems in the server/client worlds.

Dependency injection is a comfort feature that you don’t need to use, but you probably will because it makes your life a lot easier.

Often times, a system might need to use another system:

using DOTSNET;

[ServerWorld]
public class TestSystem : ComponentSystem
{
    void DoSomething()
    {
        // send a message
        GetExistingSystem<NetworkServerSystem>().Send(...);
    }

    void DoSomethingElse()
    {
        // send a message
        GetExistingSystem<NetworkServerSystem>().Send(...);
    }
}

For performance and ease of use, it makes sense to cache the system once in OnCreate:

using DOTSNET;

[ServerWorld]
public class TestSystem : ComponentSystem
{
    protected NetworkServerSystem server;

    protected override void OnCreate()
    {
        server = GetExistingSystem<NetworkServerSystem>().;
    }

    void DoSomething()
    {
        // send a message
        server.Send(...);
    }

    void DoSomethingElse()
    {
        // send a message
        server.Send(...);
    }
}

Caching all required systems in OnStartRunning can get cumbersome. This is where Dependency Injection comes in. Simply use the [AutoAssign] attribute:

using DOTSNET;

[ServerWorld]
public class TestSystem : ComponentSystem
{
    [AutoAssign] protected NetworkServerSystem server;

    void DoSomething()
    {
        // send a message
        server.Send(...);
    }

    void DoSomethingElse()
    {
        // send a message
        server.Send(...);
    }
}

DOTSNET simply initializes all [AutoAssign] systems by calling World.GetExistingSystem at startup.

  • A system in the DefaultWorld can use [AutoAssign] for any other system in the Default world.

  • A system in the ClientWorld can use [AutoAssign] for any other system in the Client world.

  • A system in the ServerWorld can use [AutoAssign] for any other system in the Server world.

Last updated