Dependency Injection

Populate a property in any class with a registered singleton using the [Inject] attribute.

First make sure you have the dependency-injection package installed:

npm init --force # only if you don't yet have a package.json file
npm install --save beatthat/dependency-injection

…then you can register any class as a singleton service like this:

using BeatThat.Service;
[RegisterService] // triggers Services to instantiate and register this class
public class Foo : MonoBehaviour, Bar
{
// implementation
}

…and you inject it to any class like this:

using BeatThat.DependencyInjection;
public class MyComponent : DependencyInjectedBehaviour
{
  [Inject] Foo foo;
}

…or you can also inject by interface

using BeatThat.DependencyInjection;
public class MyComponent : DependencyInjectedBehaviour
{
  [Inject] Bar bar; // since Foo implements Bar, generally better to injected the narrowest interface needed
}

…the DependencyInjectedBehaviour base class triggers injection for you, but you don’t have to use it. This would also work:

using BeatThat.DependencyInjection;
public class MyComponent : MonoBehaviour
{
  [Inject] Bar bar;
  void Start()
  {
    InjectDependencies.On(this);
  }
}

For code and documentation see dependency-injection.