Please note before reading: This article is based on learnings from the StarCraft II AI Framework, Abathur. It introduces a method for hiding dependency injection from the user of your framework and so might not be desirable in your case.

One of the features that the framework _‘Abathur’ _includes is the ability to add and remove components without recompiling the code. This feature is implemented through dependency injection and utilizes reflection.

The framework is responsible for the overall flow of control and the user interact with it by adding ‘components’ through a simple _IModule _interface;

public interface IModule {
  void Initialize();
  void OnStart();
  void OnStep();
  void OnGameEnded();
  void OnRestart();
}

This approach is not unique to this AI framework — it can also be seen in developing web services in NET Core where the user defines a service and the framework handles routing and the overall flow of control.

Normal Dependency Injection

The user creates their own implementation of IModule so they can interact with the framework. In our case, we will use this minimalist — and somewhat irrelevant — implementation of IModule.

public class UserCreatedModule : IModule {
  void IModule.Initialize()
    => Console.WriteLine("Initalize | UserCreatedModule");
  void IModule.OnStart()
    => Console.WriteLine("Start | UserCreatedModule");
  void IModule.OnStep()
    => Console.WriteLine("Step | UserCreatedModule");
  void IModule.OnGameEnded()
    => Console.WriteLine("Game Ended | UserCreatedModule");
  void IModule.OnRestart()
    => Console.WriteLine("Restart | UserCreatedModule");
}

If this was a regular application, and all code was written by the user, the Dependency Injection would look something like this:

public Abathur(IModule module) {
  ...
}

IServiceProvider ConfigureServices() {
  ServiceCollection services = new ServiceCollection();
  services.AddScoped<IModule, UserCreatedModule>();
  services.AddSingleton<IAbathur, Abathur>();
  return services.BuildServiceProvider();
}

#dependency-injection #artificial-intelligence #coding #programming-languages #net-core

Dependency Injection and Reflection for Frameworks in NET Core
2.60 GEEK