To use dependency injection for a field, make sure the field is writable and simply add the Ordinal attribute to that field, specifying an ordinal that will be used to determine the injection order:
using Shouldly;
using Pure.DI;
DI.Setup(nameof(Composition))
.Bind<ICoffeeMachine>().To<CoffeeMachine>()
.Bind<ISmartKitchen>().To<SmartKitchen>()
// Composition root
.Root<ISmartKitchen>("Kitchen");
var composition = new Composition();
var kitchen = composition.Kitchen;
kitchen.CoffeeMachine.ShouldBeOfType<CoffeeMachine>();
interface ICoffeeMachine;
class CoffeeMachine : ICoffeeMachine;
interface ISmartKitchen
{
ICoffeeMachine? CoffeeMachine { get; }
}
class SmartKitchen : ISmartKitchen
{
// The Dependency attribute specifies to perform an injection.
// The DI will automatically assign a value to this field
// when creating the SmartKitchen instance.
[Dependency]
public ICoffeeMachine? CoffeeMachineImpl;
// Expose the injected dependency through a public property
public ICoffeeMachine? CoffeeMachine => CoffeeMachineImpl;
}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 runThe key points are:
- The field must be writable
- The
Dependency(orOrdinal) attribute is used to mark the field for injection - The DI automatically injects the dependency when resolving the object graph
The following partial class will be generated:
partial class Composition
{
public ISmartKitchen Kitchen
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
var transientSmartKitchen293 = new SmartKitchen();
transientSmartKitchen293.CoffeeMachineImpl = new CoffeeMachine();
return transientSmartKitchen293;
}
}
}Class diagram:
---
config:
maxTextSize: 2147483647
maxEdges: 2147483647
class:
hideEmptyMembersBox: true
---
classDiagram
CoffeeMachine --|> ICoffeeMachine
SmartKitchen --|> ISmartKitchen
Composition ..> SmartKitchen : ISmartKitchen Kitchen
SmartKitchen *-- CoffeeMachine : ICoffeeMachine
namespace Pure.DI.UsageTests.Basics.FieldInjectionScenario {
class CoffeeMachine {
<<class>>
+CoffeeMachine()
}
class Composition {
<<partial>>
+ISmartKitchen Kitchen
}
class ICoffeeMachine {
<<interface>>
}
class ISmartKitchen {
<<interface>>
}
class SmartKitchen {
<<class>>
+SmartKitchen()
+ICoffeeMachine CoffeeMachineImpl
}
}