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
- Make sure you have the .NET SDK 10.0 or later installed
dotnet --list-sdk- Create a net10.0 (or later) console application
dotnet new console -n Sampledotnet 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 runNote
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()
}
}
See also: