Skip to content

Latest commit

History

History
119 lines (94 loc) 路 2.38 KB

File metadata and controls

119 lines (94 loc) 路 2.38 KB

Bind lifetime attribute

Shows how the Lifetime attribute can declare the lifetime of an implementation binding.

using Shouldly;
using Pure.DI;

DI.Setup(nameof(Composition))

    // Composition root
    .Root<IClock>("Clock");

var composition = new Composition();

composition.Clock.ShouldBeSameAs(composition.Clock);

interface IClock;

[Type(typeof(IClock))]
[Lifetime(Lifetime.Singleton)]
class SystemClock : IClock;
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

Note

A lifetime attribute on an implementation type is equivalent to applying .As(...) to the generated binding. Lifetime metadata can be specified only once inside one square-bracket binding group; repeated lifetime metadata in the same group is a compilation error.

The following partial class will be generated
partial class Composition
{
#if NET9_0_OR_GREATER
  private readonly Lock _lock = new Lock();
#else
  private readonly Object _lock = new Object();
#endif

  private SystemClock? _singletonSystemClock;

  public IClock Clock
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      if (_singletonSystemClock is null)
        lock (_lock)
          if (_singletonSystemClock is null)
          {
            _singletonSystemClock = new SystemClock();
          }

      return _singletonSystemClock;
    }
  }
}

Class diagram:

---
 config:
  class:
   hideEmptyMembersBox: true
---
classDiagram
	SystemClock --|> IClock
	Composition ..> SystemClock : IClock Clock
	namespace Pure.DI.UsageTests.Attributes.BindLifetimeAttributeScenario {
		class Composition {
		<<partial>>
		+IClock Clock
		}
		class IClock {
			<<interface>>
		}
		class SystemClock {
				<<class>>
			+SystemClock()
		}
	}
Loading

See also: