Skip to content

Latest commit

 

History

History
75 lines (57 loc) · 1.67 KB

auto-bindings.md

File metadata and controls

75 lines (57 loc) · 1.67 KB

Auto-bindings

CSharp

Injection of non-abstract types is possible without any additional effort.

class Dependency;

class Service(Dependency dependency);

// Specifies to create a partial class with name "Composition"
DI.Setup("Composition")
    // with the root "MyService"
    .Root<Service>("MyService");

var composition = new Composition();

// service = new Service(new Dependency())
var service = composition.MyService;

Warning

But this approach cannot be recommended if you follow the dependency inversion principle and want your types to depend only on abstractions.

It is better to inject abstract dependencies, for example, in the form of interfaces. Use bindings to map abstract types to their implementations as in almost all other examples.

The following partial class will be generated:

partial class Composition
{
  private readonly Composition _root;

  [OrdinalAttribute(20)]
  public Composition()
  {
    _root = this;
  }

  internal Composition(Composition parentScope)
  {
    _root = (parentScope ?? throw new ArgumentNullException(nameof(parentScope)))._root;
  }

  public Service MyService
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      return new Service(new Dependency());
    }
  }
}

Class diagram:

classDiagram
	class Composition {
		<<partial>>
		+Service MyService
	}
	class Dependency {
		+Dependency()
	}
	class Service {
		+Service(Dependency dependency)
	}
	Service *--  Dependency : Dependency
	Composition ..> Service : Service MyService
Loading