Demonstrates lazy injection using Lazy, delaying instance creation until the Value property is accessed.
using Shouldly;
using Pure.DI;
DI.Setup(nameof(Composition))
.Bind<IGraphicsEngine>().To<GraphicsEngine>()
.Bind<IWindow>().To<Window>()
// Composition root
.Root<IWindow>("Window");
var composition = new Composition();
var window = composition.Window;
// The graphics engine is created only when it is first accessed
window.Engine.ShouldBe(window.Engine);
interface IGraphicsEngine;
class GraphicsEngine : IGraphicsEngine;
interface IWindow
{
IGraphicsEngine Engine { get; }
}
class Window(Lazy<IGraphicsEngine> engine) : IWindow
{
public IGraphicsEngine Engine => engine.Value;
}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
Lazy is useful for expensive-to-create objects or when the instance may never be needed, improving application startup performance.
The following partial class will be generated:
partial class Composition
{
public IWindow Window
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
Lazy<IGraphicsEngine> transientLazy418;
// Injects an instance factory
Func<IGraphicsEngine> perBlockFunc419 = new Func<IGraphicsEngine>(
[MethodImpl(MethodImplOptions.AggressiveInlining)]
() =>
{
return new GraphicsEngine();
});
Func<IGraphicsEngine> localFactory3 = perBlockFunc419;
// Creates an instance that supports lazy initialization
transientLazy418 = new Lazy<IGraphicsEngine>(localFactory3, true);
return new Window(transientLazy418);
}
}
}Class diagram:
---
config:
maxTextSize: 2147483647
maxEdges: 2147483647
class:
hideEmptyMembersBox: true
---
classDiagram
GraphicsEngine --|> IGraphicsEngine
Window --|> IWindow
Composition ..> Window : IWindow Window
Window *-- LazyᐸIGraphicsEngineᐳ : LazyᐸIGraphicsEngineᐳ
LazyᐸIGraphicsEngineᐳ o-- "PerBlock" FuncᐸIGraphicsEngineᐳ : FuncᐸIGraphicsEngineᐳ
FuncᐸIGraphicsEngineᐳ *-- GraphicsEngine : IGraphicsEngine
namespace Pure.DI.UsageTests.BCL.LazyScenario {
class Composition {
<<partial>>
+IWindow Window
}
class GraphicsEngine {
<<class>>
+GraphicsEngine()
}
class IGraphicsEngine {
<<interface>>
}
class IWindow {
<<interface>>
}
class Window {
<<class>>
+Window(LazyᐸIGraphicsEngineᐳ engine)
}
}
namespace System {
class FuncᐸIGraphicsEngineᐳ {
<<delegate>>
}
class LazyᐸIGraphicsEngineᐳ {
<<class>>
}
}