/DIContainer

Light-weight DI Container

Primary LanguageC#OtherNOASSERTION

Introduction

Light-weight container for dynamically providing objects with the dependencies they need.

Register Mappings to the Container

ProjectContext - contains container and provide way to bind services via Installers.

Implement own installers inherit MonoInstaller, add all installers into ProjectContext

image

DependencyContainer methods

  • Bind - binding a contract type

After binding need to set a concrete type

  • To - setting a concrete realization type
  • ToSelf - setting a self concrete type
  • FromInstance - setting instance, Instance can be like a Singleton Scope
  • FromComponentInNewPrefab - Instantiate prefab and get Component
  • FromMethod - Create instance type from method

After set a conctere type set a Scope

  • AsSingle - Same instance of ResultType every time ContractType is requested, which it will lazily generate upon first use. -NonLazy - Use NonLazy method for creating istance immidiately
  • AsTransient - Every time ContractType is requested, the container will execute the given construction method again

Resolve

For Resolve use InjectAttribute for fields and properties(lazy initialization after first using) Also included injection in Constructor

[Inject] private IStateMachine Machine { get; } //will be inited when first use
[Inject] private readonly StoriesService _storiesService; //will be inited in constructor

Example

public class CustomInstaller : MonoInstaller
{
    public override void InstallBindings()
    {
        Container.Bind<IStateMachine>().To<GameStateMachine>().AsSingle(); // bind IState Machine to GameStateMachine realization as Single
        Container.Bind<IUpdater>().FromComponentInNewPrefab(_updater).AsSingle(); // binding IUpdate from prefab as Single
        Container.Bind<UserStorageService>().ToSelf().AsSingle(); // binding UserStorageService as Single
    }
}