Skip to content

Latest commit

 

History

History
129 lines (108 loc) · 2.69 KB

File metadata and controls

129 lines (108 loc) · 2.69 KB

Method injection

To use dependency injection for a method, simply add the Dependency (or Ordinal) attribute to that method, specifying the sequence number that will be used to define the call to that method:

using Shouldly;
using Pure.DI;

DI.Setup(nameof(Composition))
    .Bind<IMap>().To<Map>()
    .Bind<INavigator>().To<Navigator>()

    // Composition root
    .Root<INavigator>("Navigator");

var composition = new Composition();
var navigator = composition.Navigator;
navigator.CurrentMap.ShouldBeOfType<Map>();

interface IMap;

class Map : IMap;

interface INavigator
{
    IMap? CurrentMap { get; }
}

class Navigator : INavigator
{
    // The Dependency (or Ordinal) attribute indicates that the method
    // should be called to inject the dependency.
    [Dependency(ordinal: 0)]
    public void LoadMap(IMap map) =>
        CurrentMap = map;

    public IMap? CurrentMap { get; private set; }
}
Running this code sample locally
dotnet --list-sdk
  • Create a net10.0 (or later) console application
dotnet new console -n Sample
dotnet add package Pure.DI
dotnet add package Shouldly
  • Copy the example code into the Program.cs file

You are ready to run the example 🚀

dotnet run

The key points are:

  • The method must be available to be called from a composition class
  • The Dependency (or Ordinal) attribute is used to mark the method for injection
  • The DI automatically calls the method to inject dependencies

The following partial class will be generated:

partial class Composition
{
  public INavigator Navigator
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      var transientNavigator305 = new Navigator();
      transientNavigator305.LoadMap(new Map());
      return transientNavigator305;
    }
  }
}

Class diagram:

---
 config:
  maxTextSize: 2147483647
  maxEdges: 2147483647
  class:
   hideEmptyMembersBox: true
---
classDiagram
	Map --|> IMap
	Navigator --|> INavigator
	Composition ..> Navigator : INavigator Navigator
	Navigator *--  Map : IMap
	namespace Pure.DI.UsageTests.Basics.MethodInjectionScenario {
		class Composition {
		<<partial>>
		+INavigator Navigator
		}
		class IMap {
			<<interface>>
		}
		class INavigator {
			<<interface>>
		}
		class Map {
				<<class>>
			+Map()
		}
		class Navigator {
				<<class>>
			+Navigator()
			+LoadMap(IMap map) : Void
		}
	}
Loading