https://github.com/DevTeam/Pure.DI
Pure DI for .NET without frameworks!
https://github.com/DevTeam/Pure.DI
csharp-sourcegenerator dependency-injection di dotnet injection-container injection-framework inversion-of-control ioc pure solid
Last synced: 3 months ago
JSON representation
Pure DI for .NET without frameworks!
- Host: GitHub
- URL: https://github.com/DevTeam/Pure.DI
- Owner: DevTeam
- License: mit
- Created: 2021-03-28T05:36:20.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2024-04-13T18:03:36.000Z (over 1 year ago)
- Last Synced: 2024-04-13T19:53:52.728Z (over 1 year ago)
- Topics: csharp-sourcegenerator, dependency-injection, di, dotnet, injection-container, injection-framework, inversion-of-control, ioc, pure, solid
- Language: C#
- Homepage:
- Size: 59.8 MB
- Stars: 372
- Watchers: 5
- Forks: 20
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- RSCG_Examples - https://github.com/DevTeam/Pure.DI
- csharp-source-generators - Pure.DI -   - dependency injection for .NET without any IoC/DI containers, frameworks, dependencies, and thus without any performance impact and side-effects. (Source Generators / Dependency Injection (IoC Container))
README
# Pure DI for .NET
![]()
[](https://www.nuget.org/packages/Pure.DI)
[](LICENSE)

**Pure.DI is a compile-time dependency injection (DI) code generator**. _Supports .NET starting with [.NET Framework 2.0](https://www.microsoft.com/en-us/download/details.aspx?id=6041), released 2005-10-27, and all newer versions._
## Usage Requirements
- **[.NET SDK 6.0.4+](https://dotnet.microsoft.com/download/dotnet/6.0)**
Required for compilation. Projects can target older frameworks (e.g., .NET Framework 2.0).
- **[C# 8+](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-80)**
Only required for projects using the Pure.DI source generator. Other projects support any C# version.## Key Features
### ✔️ Zero Overhead
Pure.DI is a .NET code generator designed to produce clean, efficient dependency injection logic. By leveraging basic language constructs, it generates straightforward code indistinguishable from manual implementation—essentially composing objects through nested constructor invocations. Unlike traditional DI frameworks, Pure.DI avoids reflection and dynamic instantiation entirely, eliminating performance penalties associated with runtime overhead.
### ✔️ Compile-Time Validation
All analysis of object, constructor, and method graphs occurs at compile time. Pure.DI proactively detects and alerts developers to issues such as missing dependencies, cyclic references, or dependencies unsuitable for injection—ensuring these errors are resolved before execution. This approach guarantees that developers cannot produce a program vulnerable to runtime crashes caused by faulty dependency wiring. The validation process operates seamlessly alongside code development, creating an immediate feedback loop: as you modify your code, Pure.DI verifies its integrity in real time, effectively delivering tested, production-ready logic the moment changes are implemented.
### ✔️ Works everywhere
The pure dependency injection approach introduces no runtime dependencies and avoids .NET reflection , ensuring consistent execution across all supported platforms. This includes the Full .NET Framework 2.0+, .NET Core, .NET 5+, UWP/Xbox, .NET IoT, Unity, Xamarin, Native AOT, and beyond. By decoupling runtime constraints, it preserves predictable behavior regardless of the target environment.
### ✔️ Familiar Syntax
The Pure.DI API is intentionally designed to closely mirror the APIs of mainstream IoC/DI frameworks. This approach ensures developers can leverage their existing knowledge of dependency injection patterns without requiring significant adaptation to a proprietary syntax.
### ✔️ Precise Generics
Pure.DI recommends utilizing dedicated marker types rather than relying on open generics. This approach enables more precise construction of object graphs while allowing developers to fully leverage the capabilities of generic types.
### ✔️ Transparency
Pure.DI allows to view and debug the generated code, making debugging and testing easier.
### ✔️ Built-in BCL Support
Pure.DI provides native [support](#base-class-library) for numerous [Base Class Library (BCL)](https://docs.microsoft.com/en-us/dotnet/standard/framework-libraries#base-class-libraries) types out of the box without any extra effort.## When to Use Pure.DI
### ✔️ High-Performance Applications
Pure.DI is designed for high-performance applications where speed and minimal memory consumption are critical.
### ✔️ Projects with a Focus on Clean Code
Pure.DI is suitable for projects where code cleanliness and minimalism are important factors.
### ✔️ Applications with Complex Dependencies
Pure.DI can handle complex dependencies and provides flexible configuration options.
### ✔️ Ideal for Libraries
Its high performance, zero memory consumption/preparation overhead, and lack of dependencies make it ideal for building libraries and frameworks.## NuGet packages
| NuGet package | Description |
|-----------------------------------------------------------------------------|:--------------------------------------------------------------------|
| [Pure.DI](https://www.nuget.org/packages/Pure.DI) | DI source code generator |
| [Pure.DI.Abstractions](https://www.nuget.org/packages/Pure.DI.Abstractions) | Abstractions for Pure.DI |
| [Pure.DI.Templates](https://www.nuget.org/packages/Pure.DI.Templates) | Template package, for creating projects from the shell/command line |
| [Pure.DI.MS](https://www.nuget.org/packages/Pure.DI.MS) | Add-ons on Pure.DI to work with Microsoft DI |
## Schrödinger's cat will demonstrate how it all works [](samples/ShroedingersCat)
### The reality is

### Let's create an abstraction
```c#
interface IBox
{
T Content { get; }
}interface ICat
{
State State { get; }
}enum State { Alive, Dead }
```### Here's our implementation
```c#
record CardboardBox(T Content): IBox;class ShroedingersCat(Lazy superposition): ICat
{
// The decoherence of the superposition
// at the time of observation via an irreversible process
public State State => superposition.Value;
}
```> [!IMPORTANT]
> Our abstraction and implementation knows nothing about the magic of DI or any frameworks.### Let's glue it all together
Add the Pure.DI package to your project:
[](https://www.nuget.org/packages/Pure.DI)
Let's bind the abstractions to their implementations and set up the creation of the object graph:
```c#
DI.Setup(nameof(Composition))
// Models a random subatomic event that may or may not occur
.Bind().As(Singleton).To()
// Quantum superposition of two states: Alive or Dead
.Bind().To((Random random) => (State)random.Next(2))
.Bind().To()
// Cardboard box with any contents
.Bind().To>()
// Composition Root
.Root("Root");
```> [!NOTE]
> In fact, the `Bind().As(Singleton).To()` binding is unnecessary since Pure.DI supports many .NET BCL types out of the box, including [Random](https://github.com/DevTeam/Pure.DI/blob/27a1ccd604b2fdd55f6bfec01c24c86428ddfdcb/src/Pure.DI.Core/Features/Default.g.cs#L289). It was added just for the example of using the _Singleton_ lifetime.The above code specifies the generation of a partial class named *__Composition__*, this name is defined in the `DI.Setup(nameof(Composition))` call. This class contains a *__Root__* property that returns a graph of objects with an object of type *__Program__* as the root. The type and name of the property is defined by calling `Root("Root")`. The code of the generated class looks as follows:
```c#
partial class Composition
{
private Lock _lock = new Lock();
private Random? _random;
public Program Root
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
var stateFunc = new Func(() => {
if (_random is null)
using (_lock.EnterScope())
if (_random is null)
_random = new Random();return (State)_random.Next(2)
});return new Program(
new CardboardBox(
new ShroedingersCat(
new Lazy(
stateFunc))));
}
}public T Resolve() { ... }
public object Resolve(Type type) { ... }
}
```Obviously, this code does not depend on other libraries, does not use type reflection or any other tricks that can negatively affect performance and memory consumption. It looks like an efficient code written by hand. At any given time, you can study it and understand how it works.
The `public Program Root { get; }` property here is a [*__Composition Root__*](https://blog.ploeh.dk/2011/07/28/CompositionRoot/), the only place in the application where the composition of the object graph for the application takes place. Each instance is created by only basic language constructs, which compiles with all optimizations with minimal impact on performance and memory consumption. In general, applications may have multiple composition roots and thus such properties. Each composition root must have its own unique name, which is defined when the `Root(string name)` method is called, as shown in the above code.
### Time to open boxes!
```c#
class Program(IBox box)
{
// Composition Root, a single place in an application
// where the composition of the object graphs
// for an application take place
static void Main() => new Composition().Root.Run();private void Run() => Console.WriteLine(box);
}
```Pure.DI creates efficient code in a pure DI paradigm, using only basic language constructs as if you were writing code by hand. This allows you to take full advantage of Dependency Injection everywhere and always, without any compromise!
The full analog of this application with top-level statements can be found [here](samples/ShroedingersCatTopLevelStatements).
Just try creating a project from scratch!
Install the [projects template](https://www.nuget.org/packages/Pure.DI.Templates)
```shell
dotnet new install Pure.DI.Templates
```In some directory, create a console application
```shell
dotnet new di
```And run it
```shell
dotnet run
```## API
Pure.DI
BindAttribute
Indicates that a property or method can be automatically added as a binding.
```c#internal class DependencyProvider
{
[Bind()]
public Dependency Dep => new Dependency();
}
``````c#
internal class DependencyProvider
{
[Bind(typeof(IDependency), Lifetime.Singleton)]
public Dependency GetDep() => new Dependency();
}
``````c#
internal class DependencyProvider
{
[Bind(typeof(IDependency), Lifetime.PerResolve, "some tag")]
public Dependency GetDep(int id) => new Dependency(id);
}
```See also _Exposed_.
Constructor BindAttribute(System.Type,Pure.DI.Lifetime,System.Object[])
Creates an attribute instance.
CompositionKind
Determines how the partial class will be generated. The _Setup(System.String,Pure.DI.CompositionKind)_ method has an additional argument `kind` , which defines the type of composition:
```c#DI.Setup("BaseComposition", CompositionKind.Internal);
```See also _Setup(System.String,Pure.DI.CompositionKind)_.
Field Public
This value is used by default. If this value is specified, a normal partial class will be generated.
Field Internal
If this value is specified, the class will not be generated, but this setting can be used by other users as a baseline. The API call _DependsOn(System.String[])_ is mandatory.
Field Global
No partial classes will be created when this value is specified, but this setting is the baseline for all installations in the current project, and the API call _DependsOn(System.String[])_ is not required.
DependencyAttribute
A universal DI attribute that allows to specify the tag and ordinal of an injection.
- parameter _tag_ - The injection tag. See also _Tags(System.Object[])_
.
- parameter _ordinal_ - The injection ordinal.See also _OrdinalAttribute_.
See also _TagAttribute_.
Constructor DependencyAttribute(System.Object,System.Int32)
Creates an attribute instance.
- parameter _tag_ - The injection tag. See also _Tags(System.Object[])_
.
- parameter _ordinal_ - The injection ordinal.DI
An API for a Dependency Injection setup.
See also _Setup(System.String,Pure.DI.CompositionKind)_.Method Setup(System.String,Pure.DI.CompositionKind)
Begins the definitions of the Dependency Injection setup chain.
```c#interface IDependency;
class Dependency : IDependency;
interface IService;
class Service(IDependency dependency) : IService;
DI.Setup("Composition")
.Bind().To()
.Bind().To()
.Root("Root");
```- parameter _compositionTypeName_ - An optional argument specifying the partial class name to generate.
- parameter _kind_ - An optional argument specifying the kind of setup. Please _CompositionKind_ for details. It defaults to `Public` .
- returns Reference to the setup continuation chain.
GenericTypeArgumentAttribute
Represents a generic type argument attribute. It allows you to create custom generic type argument such as _TTS_, _TTDictionary`2_, etc.
```c#[GenericTypeArgument]
internal interface TTMy: IMy { }
```See also _GenericTypeArgumentAttribute``1_.
See also _GenericTypeArgument``1_.
Hint
Hints for the code generator and can be used to fine tune code generation.
```c#// Resolve = Off
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.Resolve, "Off")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field Resolve
`On` or `Off` . Determines whether to generate `Resolve` methods. `On` by default.
```c#// Resolve = Off
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.Resolve, "Off")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewInstance
`On` or `Off` . Determines whether to use partial `OnNewInstance` method. `Off` by default.
```c#// OnNewInstance = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewInstance, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewInstancePartial
`On` or `Off` . Determines whether to generate partial `OnNewInstance` method when the _OnNewInstance_ hint is `On` . `On` by default.
```c#// OnNewInstancePartial = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewInstancePartial, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewInstanceImplementationTypeNameRegularExpression
The regular expression to filter OnNewInstance by the instance type name. ".+" by default.
```c#// OnNewInstanceImplementationTypeNameRegularExpression = Dependency
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewInstanceImplementationTypeNameRegularExpression, "Dependency")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewInstanceImplementationTypeNameWildcard
The wildcard to filter OnNewInstance by the instance type name. "*" by default.
```c#// OnNewInstanceImplementationTypeNameWildcard = *Dependency
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewInstanceImplementationTypeNameWildcard, "*Dependency")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewInstanceTagRegularExpression
The regular expression to filter OnNewInstance by the tag. ".+" by default.
```c#// OnNewInstanceTagRegularExpression = IDependency
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewInstanceTagRegularExpression, "IDependency")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewInstanceTagWildcard
The wildcard to filter OnNewInstance by the tag. "*" by default.
```c#// OnNewInstanceTagWildcard = *IDependency
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewInstanceTagWildcard, "*IDependency")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewInstanceLifetimeRegularExpression
The regular expression to filter OnNewInstance by the lifetime. ".+" by default.
```c#// OnNewInstanceLifetimeRegularExpression = Singleton
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewInstanceLifetimeRegularExpression, "Singleton")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewInstanceLifetimeWildcard
The wildcard to filter OnNewInstance by the lifetime. "*" by default.
```c#// OnNewInstanceLifetimeWildcard = *Singleton
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewInstanceLifetimeWildcard, "*Singleton")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjection
`On` or `Off` . Determines whether to use partial `OnDependencyInjection` method to control of dependency injection. `Off` by default.
```c#// OnDependencyInjection = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjection, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionPartial
`On` or `Off` . Determines whether to generate partial `OnDependencyInjection` method when the _OnDependencyInjection_ hint is `On` to control of dependency injection. `On` by default.
```c#// OnDependencyInjectionPartial = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionPartial, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionImplementationTypeNameRegularExpression
The regular expression to filter OnDependencyInjection by the instance type name. ".+" by default.
```c#// OnDependencyInjectionImplementationTypeNameRegularExpression = Dependency
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionImplementationTypeNameRegularExpression, "Dependency")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionImplementationTypeNameWildcard
The wildcard to filter OnDependencyInjection by the instance type name. "*" by default.
```c#// OnDependencyInjectionImplementationTypeNameWildcard = *Dependency
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionImplementationTypeNameWildcard, "*Dependency")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionContractTypeNameRegularExpression
The regular expression to filter OnDependencyInjection by the resolving type name. ".+" by default.
```c#// OnDependencyInjectionContractTypeNameRegularExpression = IDependency
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionContractTypeNameRegularExpression, "IDependency")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionContractTypeNameWildcard
The wildcard to filter OnDependencyInjection by the resolving type name. "*" by default.
```c#// OnDependencyInjectionContractTypeNameWildcard = *IDependency
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionContractTypeName, "*IDependency")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionTagRegularExpression
The regular expression to filter OnDependencyInjection by the tag. ".+" by default.
```c#// OnDependencyInjectionTagRegularExpression = MyTag
DI.Setup("Composition")
.Bind("MyTag").To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionTagRegularExpression, "MyTag")
.Bind("MyTag").To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionTagWildcard
The wildcard to filter OnDependencyInjection by the tag. "*" by default.
```c#// OnDependencyInjectionTagWildcard = MyTag
DI.Setup("Composition")
.Bind("MyTag").To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionTagWildcard, "MyTag")
.Bind("MyTag").To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionLifetimeRegularExpression
The regular expression to filter OnDependencyInjection by the lifetime. ".+" by default.
```c#// OnDependencyInjectionLifetimeRegularExpression = Singleton
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionLifetimeRegularExpression, "Singleton")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnDependencyInjectionLifetimeWildcard
The wildcard to filter OnDependencyInjection by the lifetime. ".+" by default.
```c#// OnDependencyInjectionLifetimeWildcard = *Singleton
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnDependencyInjectionLifetimeWildcard, "*Singleton")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnCannotResolve
`On` or `Off` . Determines whether to use a partial `OnCannotResolve(...)` method to handle a scenario in which the dependency cannot be resolved. `Off` by default.
```c#// OnCannotResolve = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnCannotResolve, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnCannotResolvePartial
`On` or `Off` . Determines whether to generate a partial `OnCannotResolve(...)` method when the `OnCannotResolve` hint is `On` to handle a scenario in which the dependency cannot be resolved. `On` by default.
```c#// OnCannotResolvePartial = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnCannotResolvePartial, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnCannotResolveContractTypeNameRegularExpression
The regular expression to filter OnCannotResolve by the resolving type name. ".+" by default.
```c#// OnCannotResolveContractTypeNameRegularExpression = OtherType
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnCannotResolveContractTypeNameRegularExpression, "OtherType")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnCannotResolveContractTypeNameWildcard
The wildcard to filter OnCannotResolve by the resolving type name. "*" by default.
```c#// OnCannotResolveContractTypeNameWildcard = *OtherType
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnCannotResolveContractTypeNameWildcard, "*OtherType")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnCannotResolveTagRegularExpression
The regular expression to filter OnCannotResolve by the tag. ".+" by default.
```c#// OnCannotResolveTagRegularExpression = MyTag
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnCannotResolveTagRegularExpression, "MyTag")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnCannotResolveTagWildcard
The wildcard to filter OnCannotResolve by the tag. "*" by default.
```c#// OnCannotResolveTagWildcard = MyTag
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnCannotResolveTagWildcard, "MyTag")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnCannotResolveLifetimeRegularExpression
The regular expression to filter OnCannotResolve by the lifetime. ".+" by default.
```c#// OnCannotResolveLifetimeRegularExpression = Singleton
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnCannotResolveLifetimeRegularExpression, "Singleton")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnCannotResolveLifetimeWildcard
The wildcard to filter OnCannotResolve by the lifetime. "*" by default.
```c#// OnCannotResolveLifetimeWildcard = *Singleton
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnCannotResolveLifetimeWildcard, "*Singleton")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewRoot
`On` or `Off` . Determines whether to use a static partial `OnNewRoot(...)` method to handle the new composition root registration event. `Off` by default.
```c#// OnNewRoot = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewRoot, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field OnNewRootPartial
`On` or `Off` . Determines whether to generate a static partial `OnNewRoot(...)` method when the `OnNewRoot` hint is `On` to handle the new composition root registration event. `On` by default.
```c#// OnNewRootPartial = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.OnNewRootPartial, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ToString
`On` or `Off` . Determine if the `ToString()` method should be generated. This method provides a text-based class diagram in the format mermaid. `Off` by default.
```c#// ToString = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ToString, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ThreadSafe
`On` or `Off` . This hint determines whether object composition will be created in a thread-safe manner. `On` by default.
```c#// ThreadSafe = Off
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ThreadSafe, "Off")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ResolveMethodModifiers
Overrides modifiers of the method `public T Resolve()` . "public" by default.
```c#// ResolveMethodModifiers = internal
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ResolveMethodModifiers, "internal")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ResolveMethodName
Overrides name of the method `public T Resolve()` . "Resolve" by default.
```c#// ResolveMethodName = GetService
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ResolveMethodName, "GetService")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ResolveByTagMethodModifiers
Overrides modifiers of the method `public T Resolve(object? tag)` . "public" by default.
```c#// ResolveByTagMethodModifiers = internal
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ResolveByTagMethodModifiers, "internal")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ResolveByTagMethodName
Overrides name of the method `public T Resolve(object? tag)` . "Resolve" by default.
For example:
```c#// ResolveByTagMethodName = GetService
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ResolveByTagMethodName, "GetService")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ObjectResolveMethodModifiers
Overrides modifiers of the method `public object Resolve(Type type)` . "public" by default.
```c#// ObjectResolveMethodModifiers = internal
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ObjectResolveMethodModifiers, "internal")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ObjectResolveMethodName
Overrides name of the method `public object Resolve(Type type)` . "Resolve" by default.
```c#// ObjectResolveMethodName = GetService
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ObjectResolveMethodName, "GetService")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ObjectResolveByTagMethodModifiers
Overrides modifiers of the method `public object Resolve(Type type, object? tag)` . "public" by default.
```c#// ObjectResolveByTagMethodModifiers = internal
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ObjectResolveByTagMethodModifiers, "internal")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field ObjectResolveByTagMethodName
Overrides name of the method `public object Resolve(Type type, object? tag)` . "Resolve" by default.
```c#// ObjectResolveByTagMethodName = GetService
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.ObjectResolveByTagMethodName, "GetService")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field DisposeMethodModifiers
Overrides modifiers of the method `public void Dispose()` . "public" by default.
```c#// DisposeMethodModifiers = internal
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.DisposeMethodModifiers, "internal")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field DisposeAsyncMethodModifiers
Overrides modifiers of the method `public _ValueTask_ DisposeAsyncMethodModifiers()` . "public" by default.
```c#// DisposeAsyncMethodModifiers = internal
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.DisposeAsyncMethodModifiers, "internal")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field FormatCode
`On` or `Off` . Specifies whether the generated code should be formatted. This option consumes a lot of CPU resources. `Off` by default.
```c#// FormatCode = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.FormatCode, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field SeverityOfNotImplementedContract
`Error` or `Warning` or `Info` or `Hidden` . Indicates the severity level of the situation when, in the binding, an implementation does not implement a contract. `Error` by default.
```c#// FormatCode = On
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.SeverityOfNotImplementedContracts, "On")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field Comments
`On` or `Off` . Specifies whether the generated code should be commented. `On` by default.
```c#// Comments = Off
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.Comments, "Off")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
Field SystemThreadingLock
`On` or `Off` . Indicates whether _Lock_ should be used whenever possible instead of the classic approach of synchronizing object access using _Monitor_. `On` by default.
```c#// SystemThreadingLock = Off
DI.Setup("Composition")
.Bind().To();
```or using the API call _Hint(Pure.DI.Hint,System.String)_:
```c#DI.Setup("Composition")
.Hint(Hint.SystemThreadingLock, "Off")
.Bind().To();
```See also _Hint(Pure.DI.Hint,System.String)_.
IBinding
An API for a binding setup.
Method Bind(System.Object[])Begins the binding definition for the implementation type itself, and if the implementation is not an abstract class or structure, for all abstract but NOT special types that are directly implemented.
Special types include:
System.ObjectSystem.EnumSystem.MulticastDelegateSystem.DelegateSystem.Collections.IEnumerableSystem.Collections.Generic.IEnumerableSystem.Collections.Generic.IListSystem.Collections.Generic.ICollectionSystem.Collections.IEnumeratorSystem.Collections.Generic.IEnumeratorSystem.Collections.Generic.IIReadOnlyListSystem.Collections.Generic.IReadOnlyCollectionSystem.IDisposableSystem.IAsyncResultSystem.AsyncCallback
```c#DI.Setup("Composition")
.Bind().To();
```- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.
- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _!:To()_.
See also _!:To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method Bind``1(System.Object[])
Begins the definition of the binding.
```c#DI.Setup("Composition")
.Bind().To();
```The type of dependency to be bound. Common type markers such as _TT_, _TTList`1_ and others are also supported.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _!:To()_.
See also _!:To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method Bind``2(System.Object[])
Begins binding definition for multiple dependencies. See _Bind``1(System.Object[])_ for examples.
The type 1 of dependency to be bound.The type 2 of dependency to be bound.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _!:To()_.
See also _!:To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method Bind``3(System.Object[])
Begins binding definition for multiple dependencies. See _Bind``1(System.Object[])_ for examples.
The type 1 of dependency to be bound.The type 2 of dependency to be bound.The type 3 of dependency to be bound.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _!:To()_.
See also _!:To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method Bind``4(System.Object[])
Begins binding definition for multiple dependencies. See _Bind``1(System.Object[])_ for examples.
The type 1 of dependency to be bound.The type 2 of dependency to be bound.The type 3 of dependency to be bound.The type 3 of dependency to be bound.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _!:To()_.
See also _!:To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method As(Pure.DI.Lifetime)
Determines the _Lifetime_ of a binding.
```c#DI.Setup("Composition")
.Bind().As(Lifetime.Singleton).To();
```- parameter _lifetime_ - The _Lifetime_ of a binding
- returns Reference to the setup continuation chain.
See also _Bind``1(System.Object[])_.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _!:To()_.
See also _!:To()_.
See also _Tags(System.Object[])_.
Method Tags(System.Object[])
Defines the binding tags.
Sometimes it's important to take control of building a dependency graph. For example, when there are multiple implementations of the same contract. In this case, tags will help:
```c#interface IDependency { }
class AbcDependency : IDependency { }
class XyzDependency : IDependency { }
class Dependency : IDependency { }
interface IService
{
IDependency Dependency1 { get; }
IDependency Dependency2 { get; }
}
class Service : IService
{
public Service(
[Tag("Abc")] IDependency dependency1,
[Tag("Xyz")] IDependency dependency2)
{
Dependency1 = dependency1;
Dependency2 = dependency2;
}
public IDependency Dependency1 { get; }
public IDependency Dependency2 { get; }
}
DI.Setup("Composition")
.Bind().Tags("Abc").To()
.Bind().Tags("Xyz").To()
.Bind().To().Root("Root");
```- parameter _tags_ - The binding tags.
- returns Reference to the setup continuation chain.
See also _Bind``1(System.Object[])_.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _!:To()_.
See also _!:To()_.
See also _As(Pure.DI.Lifetime)_.
Method To``1
Completes the binding chain by specifying the implementation.
```c#DI.Setup("Composition")
.Bind().To();
```The implementation type. Also supports generic type markers such as _TT_, _TTList`1_, and others.
- returns Reference to the setup continuation chain.See also _Bind``1(System.Object[])_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _!:To()_.
See also _!:To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method To``1(System.Func{Pure.DI.IContext,``0})
Completes the binding chain by specifying the implementation using a factory method. It allows you to manually create an instance, call the necessary methods, initialize properties, fields, etc.
```c#DI.Setup("Composition")
.Bind()
To(_ =>
{
var service = new Service("My Service");
service.Initialize();
return service;
})
```another example:
```c#DI.Setup("Composition")
.Bind<IService>()
To(ctx =>
{
ctx.Inject(out var dependency);
return new Service(dependency);
})
```and another example:
```c#DI.Setup("Composition")
.Bind<IService>()
To(ctx =>
{
// Builds up an instance with all necessary dependencies
ctx.Inject(out var service);
service.Initialize();
return service;
})
```- parameter _factory_ - An expression for manually creating and initializing an instance.
The implementation type.
- returns Reference to the setup continuation chain.See also _Bind``1(System.Object[])_.
See also _To``1_.
See also _!:To()_.
See also _!:To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method To``1(System.String)
Completes the binding chain by specifying the implementation using a source code statement.
```c#DI.Setup("Composition")
.Bind().To("dependencyId")
.Bind>()
.To>(ctx =>
dependencyId =>
{
ctx.Inject(out var dependency);
return dependency;
});
```- parameter _sourceCodeStatement_ - Source code statement
The implementation type.
- returns Reference to the setup continuation chain.See also _Bind``1(System.Object[])_.
Method To``2(System.Func{``0,``1})
Completes the binding chain by specifying the implementation using a simplified factory method. It allows you to manually create an instance, call the necessary methods, initialize properties, fields, etc. Each parameter of this factory method represents a dependency injection. Starting with C# 10, you can also put the _TagAttribute_ in front of the parameter to specify the tag of the injected dependency.
```c#DI.Setup(nameof(Composition))
.Bind().To((
Dependency dependency) =>
{
dependency.Initialize();
return dependency;
});
```A variant using _TagAttribute_:
```c#DI.Setup(nameof(Composition))
.Bind().To((
[Tag("some tag")] Dependency dependency) =>
{
dependency.Initialize();
return dependency;
});
```- parameter _factory_ - An expression for manually creating and initializing an instance.
Type #1 of injected dependency.The implementation type.
- returns Reference to the setup continuation chain.See also _Bind``1(System.Object[])_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To``1_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method To``3(System.Func{``0,``1,``2})
Completes the binding chain by specifying the implementation using a simplified factory method. It allows you to manually create an instance, call the necessary methods, initialize properties, fields, etc. Each parameter of this factory method represents a dependency injection. Starting with C# 10, you can also put the _TagAttribute_ in front of the parameter to specify the tag of the injected dependency.
```c#DI.Setup(nameof(Composition))
.Bind().To((
Dependency dependency,
DateTimeOffset time) =>
{
dependency.Initialize(time);
return dependency;
});
```A variant using _TagAttribute_:
```c#DI.Setup(nameof(Composition))
.Bind("now datetime").To(_ => DateTimeOffset.Now)
.Bind().To((
Dependency dependency,
[Tag("now datetime")] DateTimeOffset time) =>
{
dependency.Initialize(time);
return dependency;
});
```- parameter _factory_ - An expression for manually creating and initializing an instance.
Type #1 of injected dependency.Type #2 of injected dependency.The implementation type.
- returns Reference to the setup continuation chain.See also _Bind``1(System.Object[])_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To``1_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method To``4(System.Func{``0,``1,``2,``3})
Completes the binding chain by specifying the implementation using a simplified factory method. It allows you to manually create an instance, call the necessary methods, initialize properties, fields, etc. Each parameter of this factory method represents a dependency injection. Starting with C# 10, you can also put the _TagAttribute_ in front of the parameter to specify the tag of the injected dependency.
- parameter _factory_ - An expression for manually creating and initializing an instance.
Type #1 of injected dependency.Type #2 of injected dependency.Type #3 of injected dependency.The implementation type.
- returns Reference to the setup continuation chain.See also _Bind``1(System.Object[])_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To``1_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
IConfiguration
An API for a Dependency Injection setup.
See also _Setup(System.String,Pure.DI.CompositionKind)_.Method Bind(System.Object[])
Begins the binding definition for the implementation type itself, and if the implementation is not an abstract class or structure, for all abstract but NOT special types that are directly implemented.
Special types include:
System.ObjectSystem.EnumSystem.MulticastDelegateSystem.DelegateSystem.Collections.IEnumerableSystem.Collections.Generic.IEnumerableSystem.Collections.Generic.IListSystem.Collections.Generic.ICollectionSystem.Collections.IEnumeratorSystem.Collections.Generic.IEnumeratorSystem.Collections.Generic.IIReadOnlyListSystem.Collections.Generic.IReadOnlyCollectionSystem.IDisposableSystem.IAsyncResultSystem.AsyncCallback
```c#DI.Setup("Composition")
.Bind().To();
```- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.
- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To()_.
See also _To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method Bind``1(System.Object[])
Begins the definition of the binding.
```c#DI.Setup("Composition")
.Bind().To();
```The type of dependency to be bound.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To()_.
See also _To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method Bind``2(System.Object[])
Begins binding definition for multiple dependencies. See _Bind``1(System.Object[])_ for examples.
The type 1 of dependency to be bound.The type 2 of dependency to be bound.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To()_.
See also _To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method Bind``3(System.Object[])
Begins binding definition for multiple dependencies. See _Bind``1(System.Object[])_ for examples.
The type 1 of dependency to be bound.The type 2 of dependency to be bound.The type 3 of dependency to be bound.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To()_.
See also _To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method Bind``4(System.Object[])
Begins binding definition for multiple dependencies. See _Bind``1(System.Object[])_ for examples.
The type 1 of dependency to be bound.The type 2 of dependency to be bound.The type 3 of dependency to be bound.The type 4 of dependency to be bound.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding.- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To()_.
See also _To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method RootBind``1(System.String,Pure.DI.RootKinds,System.Object[])
Begins the definition of the binding with _Root``1(System.String,System.Object,Pure.DI.RootKinds)_ applied.
```c#DI.Setup("Composition")
.RootBind();
```The type of dependency to be bound.
- parameter _name_ - Specifies the name of the root of the composition. If the value is empty, a private root will be created, which can be used when calling `Resolve` methods.
The name supports templating:
TemplateDescription{type}Will be replaced by the short name of the root type without its namespaces.{TYPE}Will be replaced with the full name of the root type.{tag}Will be replaced with the first tag name.- parameter _kind_ - The optional argument specifying the kind for the root of the composition.
- parameter _tags_ - The optional argument that specifies tags for a particular type of dependency binding. If is is not empty, the first tag is used for the root.
- returns Reference to the setup continuation chain.
See also _To``1_.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _To()_.
See also _To()_.
See also _Tags(System.Object[])_.
See also _As(Pure.DI.Lifetime)_.
Method DependsOn(System.String[])
Indicates the use of some single or multiple setups as base setups by name.
```c#DI.Setup("Composition")
.DependsOn(nameof(CompositionBase));
```- parameter _setupNames_ - A set of names for the basic setups on which this one depends.
- returns Reference to the setup continuation chain.
See also _Setup(System.String,Pure.DI.CompositionKind)_.
Method GenericTypeArgumentAttribute``1
Specifies a custom generic type argument attribute.
```c#[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
class MyGenericTypeArgumentAttribute : Attribute;
[MyGenericTypeArgument]
interface TTMy;
DI.Setup("Composition")
.GenericTypeAttribute()
.Bind>().To>();
```The attribute type.
- returns Reference to the setup continuation chain.See also _GenericTypeArgumentAttribute``1_.
Method TypeAttribute``1(System.Int32)
Specifies a custom attribute that overrides the injection type.
```c#DI.Setup("Composition")
.TypeAttribute();
```- parameter _typeArgumentPosition_ - The optional parameter that specifies the position of the type parameter in the attribute constructor. 0 by default. See predefined attribute _TypeAttribute``1(System.Int32)_.
The attribute type.
- returns Reference to the setup continuation chain.See also _TypeAttribute_.
Method TagAttribute``1(System.Int32)
Specifies a tag attribute that overrides the injected tag.
```c#DI.Setup("Composition")
.TagAttribute();
```- parameter _tagArgumentPosition_ - The optional parameter that specifies the position of the tag parameter in the attribute constructor. 0 by default. See the predefined _TagAttribute``1(System.Int32)_ attribute.
The attribute type.
- returns Reference to the setup continuation chain.See also _TagAttribute_.
Method OrdinalAttribute``1(System.Int32)
Specifies a custom attribute that overrides the injection ordinal.
```c#DI.Setup("Composition")
.OrdinalAttribute();
```- parameter _ordinalArgumentPosition_ - The optional parameter that specifies the position of the ordinal parameter in the attribute constructor. 0 by default. See the predefined _OrdinalAttribute``1(System.Int32)_ attribute.
The attribute type.
- returns Reference to the setup continuation chain.See also _OrdinalAttribute_.
Method DefaultLifetime(Pure.DI.Lifetime)
Overrides the default _Lifetime_ for all bindings further down the chain. If not specified, the _Transient_ lifetime is used.
```c#DI.Setup("Composition")
.DefaultLifetime(Lifetime.Singleton);
```- parameter _lifetime_ - The default lifetime.
- returns Reference to the setup continuation chain.
See also _Lifetime_.
See also _As(Pure.DI.Lifetime)_.
Method DefaultLifetime``1(Pure.DI.Lifetime,System.Object[])
Overrides the default _Lifetime_ for all bindings can be casted to type further down the chain.
```c#DI.Setup("Composition")
.DefaultLifetime(Lifetime.Singleton);
``````c#
DI.Setup("Composition")
.DefaultLifetime(Lifetime.Singleton, "my tag");
```- parameter _lifetime_ - The default lifetime.
- parameter _tags_ - The optional argument specifying the binding tags for which it will set the default lifetime. If not specified, the default lifetime will be set for any tags.
The default lifetime will be applied to bindings if the implementation class can be cast to type .
- returns Reference to the setup continuation chain.See also _Lifetime_.
See also _As(Pure.DI.Lifetime)_.
Method Arg``1(System.String,System.Object[])
Adds a partial class argument and replaces the default constructor by adding this argument as a parameter. It is only created if this argument is actually used.
```c#DI.Setup("Composition")
.Arg("id");
```- parameter _name_ - The argument name.
The name supports templating:
TemplateDescription{type}Will be replaced by the short name of the argument type without its namespaces.{TYPE}Will be replaced with the full name of the argument type.{tag}Will be replaced with the first tag name.- parameter _tags_ - The optional argument that specifies the tags for the argument.
The argument type.
- returns Reference to the setup continuation chain.See also _RootArg``1(System.String,System.Object[])_.
Method RootArg``1(System.String,System.Object[])
Adds a root argument to use as a root parameter.
```c#DI.Setup("Composition")
.RootArg("id");
```- parameter _name_ - The argument name.
The name supports templating:
TemplateDescription{type}Will be replaced by the short name of the argument type without its namespaces.{TYPE}Will be replaced with the full name of the argument type.{tag}Will be replaced with the first tag name.- parameter _tags_ - The optional argument that specifies the tags for the argument.
The argument type.
- returns Reference to the setup continuation chain.See also _Arg``1(System.String,System.Object[])_.
Method Root``1(System.String,System.Object,Pure.DI.RootKinds)
Specifying the root of the composition.
```c#DI.Setup("Composition")
.Root("MyService");
``````c#
DI.Setup("Composition")
.Root("My{type}");
```- parameter _name_ - Specifies the name of the root of the composition. If the value is empty, a private root will be created, which can be used when calling `Resolve` methods.
The name supports templating:
TemplateDescription{type}Will be replaced by the short name of the root type without its namespaces.{TYPE}Will be replaced with the full name of the root type.{tag}Will be replaced with the root tag name.- parameter _tag_ - The optional argument specifying the tag for the root of the composition.
- parameter _kind_ - The optional argument specifying the kind for the root of the composition.
The composition root type.
- returns Reference to the setup continuation chain.See also _RootBind``1(System.String,Pure.DI.RootKinds,System.Object[])_.
See also _Roots``1(System.String,Pure.DI.RootKinds,System.String)_.
Method Roots``1(System.String,Pure.DI.RootKinds,System.String)
Specifies to define composition roots for all types inherited from _!:T_ available at compile time at the point where the method is called.
```c#DI.Setup("Composition")
.Roots();
``````c#
DI.Setup("Composition")
.Roots("Root{type}", filter: "*MyService");
```- parameter _name_ - Specifies the name of the roots of the composition. If the value is empty, private roots will be created, which can be used when calling `Resolve` methods.
The name supports templating:
TemplateDescription{type}Will be replaced by the short name of the type without its namespaces.{TYPE}Will be replaced with the full name of the type.- parameter _kind_ - The optional argument specifying the kind for the root of the composition.
- parameter _filter_ - A wildcard to filter root types by their full name.
The composition root base type.
- returns Reference to the setup continuation chain.See also _Root``1(System.String,System.Object,Pure.DI.RootKinds)_.
Method Builder``1(System.String,Pure.DI.RootKinds)
Specifies the method of the composition builder. The first argument to the method will always be the instance to be built. The remaining arguments to this method will be listed in the order in which they are defined in the setup.Specifies to create a composition builder method. The first argument to the method will always be the instance to be built. The remaining arguments to this method will be listed in the order in which they are defined in the setup.
```c#DI.Setup("Composition")
.Builder("BuildUpMyService");
```- parameter _name_ - Specifies the name of the builder. The default name is "BuildUp".
The name supports templating:
TemplateDescription{type}Will be replaced by the short name of the type without its namespaces.{TYPE}Will be replaced with the full name of the type.- parameter _kind_ - The optional argument specifying the kind for the root of the composition.
The composition root type.
- returns Reference to the setup continuation chain.See also _Builders``1(System.String,Pure.DI.RootKinds,System.String)_.
Method Builders``1(System.String,Pure.DI.RootKinds,System.String)
Specifies to define builders for all types inherited from _!:T_ available at compile time at the point where the method is called.
```c#DI.Setup("Composition")
.Builders();
``````c#
DI.Setup("Composition")
.Builder("BuildUp");
``````c#
DI.Setup("Composition")
.Builder("BuildUp{type}", filter: "*MyService");
```- parameter _name_ - Specifies the name of the builders. The default name is "BuildUp".
The name supports templating:
TemplateDescription{type}Will be replaced by the short name of the type without its namespaces.{TYPE}Will be replaced with the full name of the type.- parameter _kind_ - The optional argument specifying the kind for the root of the composition.
- parameter _filter_ - A wildcard to filter builder types by their full name.
The composition root base type.
- returns Reference to the setup continuation chain.See also _Builder``1(System.String,Pure.DI.RootKinds)_.
Method Hint(Pure.DI.Hint,System.String)
Defines a hint for fine-tuning code generation.
```c#DI.Setup("Composition")
.Hint(Resolve, "Off");
```- parameter _hint_ - The hint type.
- parameter _value_ - The hint value.
- returns Reference to the setup continuation chain.
See also _Hint_.
Method Accumulate``2(Pure.DI.Lifetime[])
Registers an accumulator for instances.
```c#DI.Setup("Composition")
.Accumulate(Lifetime.Transient);
```- parameter _lifetimes_ - _Lifetime_ of the instances to be accumulated. Instances with lifetime _Singleton_, _Scoped_, or _PerResolve_ only accumulate in an accumulator that is NOT lazily created.
The type of instance. All instances that can be cast to this type will be aacumulated.The type of accumulator. It must have a public constructor without parameters and a `Add` method with a single argument that allows you to add an instance of type .
- returns Reference to the setup continuation chain.See also _Lifetime_.
Method GenericTypeArgument``1
Specifies a custom generic type argument.
```c#interface TTMy;
DI.Setup("Composition")
.GenericTypeArgument()
.Bind>().To>();
```The generic type marker.
- returns Reference to the setup continuation chain.See also _GenericTypeArgumentAttribute``1_.
IContext
Injection context. Cannot be used outside of the binding setup.
Property TagThe tag that was used to inject the current object in the object graph. Cannot be used outside of the binding setup. See also _Tags(System.Object[])_
```c#DI.Setup("Composition")
.Bind>()
.To(ctx =>
{
ctx.Inject>(ctx.Tag, out var func);
return new Lazy(func, false);
};
```See also _To``1(System.Func{Pure.DI.IContext,``0})_.
See also _Tags(System.Object[])_.
Property ConsumerTypes
The types of consumers for which the instance is created. Cannot be used outside of the binding setup. Guaranteed to contain at least one element.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.Method Inject``1(``0@)
Injects an instance of type `T` . Cannot be used outside of the binding setup.
```c#DI.Setup("Composition")
.Bind()
To(ctx =>
{
ctx.Inject(out var dependency);
return new Service(dependency);
})
```and another example:
```c#DI.Setup("Composition")
.Bind()
To(ctx =>
{
// Builds up an instance with all necessary dependencies
ctx.Inject(out var service);
service.Initialize();
return service;
})
```- parameter _value_ - Injectable instance.
.
Instance type.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.Method Inject``1(System.Object,``0@)
Injects an instance of type `T` marked with a tag. Cannot be used outside of the binding setup.
```c#DI.Setup("Composition")
.Bind()
To(ctx =>
{
ctx.Inject("MyTag", out var dependency);
return new Service(dependency);
})
```- parameter _tag_ - The injection tag. See also _Tags(System.Object[])_
.
- parameter _value_ - Injectable instance.
.
Instance type.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.Method BuildUp``1(``0)
Builds up of an existing object. In other words, injects the necessary dependencies via methods, properties, or fields into an existing object. Cannot be used outside of the binding setup.
```c#DI.Setup("Composition")
.Bind()
To(ctx =>
{
var service = new Service();
// Initialize an instance with all necessary dependencies
ctx.BuildUp(service);
return service;
})
```- parameter _value_ - An existing object for which the injection(s) is to be performed.
Object type.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.Method Override``1(``0,System.Object[])
Overrides the binding with the specified value. Cannot be used outside of the binding setting.
```c#DI.Setup("Composition")
.Bind().To>(ctx =>
(dependencyId, subId) =>
{
// Overrides with a lambda argument
ctx.Override(dependencyId);
// Overrides with tag using lambda argument
ctx.Override(subId, "sub");
// Overrides with some value
ctx.Override($"Dep {dependencyId} {subId}");
// Overrides with injected value
ctx.Inject(Tag.Red, out Color red);
ctx.Override(red);
ctx.Inject(out var dependency);
return dependency;
})
```- parameter _value_ - The object that will be used to override a binding.
Object type that will be used to override a binding.
- parameter _tags_ - Injection tags that will be used to override a binding. See also _Tags(System.Object[])_
.
See also _To``1(System.Func{Pure.DI.IContext,``0})_.IOwned
This abstraction allows a disposable object to be disposed of.
See also _Owned_.See also _Accumulate``2(Pure.DI.Lifetime[])_.
Lifetime
Binding lifetimes.
```c#DI.Setup("Composition")
.Bind().As(Lifetime.Singleton).To();
```See also _Setup(System.String,Pure.DI.CompositionKind)_.
See also _As(Pure.DI.Lifetime)_.
See also _DefaultLifetime(Pure.DI.Lifetime)_.
See also _DefaultLifetime``1(Pure.DI.Lifetime,System.Object[])_.
Field Transient
Specifies to create a new dependency instance each time. This is the default value and can be omitted.
```c#DI.Setup("Composition")
.Bind().As(Lifetime.Transient).To();
```This is the default lifetime, it can be omitted, for example:
```c#DI.Setup("Composition")
.Bind().To();
```Field Singleton
Ensures that there will be a single instance of the dependency for each composition.
```c#DI.Setup("Composition")
.Bind().As(Lifetime.Singleton).To();
```Field PerResolve
Guarantees that there will be a single instance of the dependency for each root of the composition.
```c#DI.Setup("Composition")
.Bind().As(Lifetime.PerResolve).To();
```Field PerBlock
Does not guarantee that there will be a single instance of the dependency for each root of the composition, but is useful to reduce the number of instances of type.
```c#DI.Setup("Composition")
.Bind().As(Lifetime.PerBlock).To();
```Field Scoped
Ensures that there will be a single instance of the dependency for each scope.
```c#DI.Setup("Composition")
.Bind().As(Lifetime.Singleton).To();
```Name
Represents well known names.
OrdinalAttribute
Represents an ordinal attribute.
This attribute is part of the API, but you can use your own attribute at any time, and this allows you to define them in the assembly and namespace you want.
For constructors, it defines the sequence of attempts to use a particular constructor to create an object:
```c#class Service : IService
{
private readonly string _name;
[Ordinal(1)]
public Service(IDependency dependency) =>
_name = "with dependency";
[Ordinal(0)]
public Service(string name) => _name = name;
}
```For fields, properties and methods, it specifies to perform dependency injection and defines the sequence:
```c#class Person : IPerson
{
private readonly string _name = "";
[Ordinal(0)]
public int Id;
[Ordinal(1)]
public string FirstName
{
set
{
_name = value;
}
}
public IDependency? Dependency { get; private set; }
[Ordinal(2)]
public void SetDependency(IDependency dependency) =>
Dependency = dependency;
}
```See also _DependencyAttribute_.
See also _TagAttribute_.
See also _TypeAttribute_.
Constructor OrdinalAttribute(System.Int32)
Creates an attribute instance.
- parameter _ordinal_ - The injection ordinal.Owned
Performs accumulation and disposal of disposable objects.
See also _IOwned_.See also _Accumulate``2(Pure.DI.Lifetime[])_.
Method Dispose
Owned`1
Contains a value and gives the ability to dispose of that value.
Type of value owned.
See also _IOwned_.See also _Owned_.
See also _Accumulate``2(Pure.DI.Lifetime[])_.
Field Value
Own value.
Constructor Owned`1(`0,Pure.DI.IOwned)
Creates a new instance.
- parameter _value_ - Own value.- parameter _owned_ - The abstraction allows a disposable object to be disposed of.
Method Dispose
RootKinds
Determines a kind of root of the composition.
See also _Root``1(System.String,System.Object,Pure.DI.RootKinds)_.See also _RootBind``1(System.String,Pure.DI.RootKinds,System.Object[])_.
See also _Roots``1(System.String,Pure.DI.RootKinds,System.String)_.
See also _Builder``1(System.String,Pure.DI.RootKinds)_.
See also _Builders``1(System.String,Pure.DI.RootKinds,System.String)_.
Field Default
Specifies to use the default composition root kind.
Field Public
Specifies to use a `public` access modifier for the root of the composition.
Field Internal
Specifies to use a `internal` access modifier for the root of the composition.
Field Private
Specifies to use a `private` access modifier for the root of the composition.
Field Property
Specifies to create a composition root as a property.
Field Method
Specifies to create a composition root as a method.
Field Static
Specifies to create a static root of the composition.
Field Partial
Specifies to create a partial root of the composition.
Field Exposed
Specifies to create a exposed root of the composition.
See also _BindAttribute_.Field Protected
Specifies to use a `protected` access modifier for the root of the composition.
Tag
Represents well known tags.
See also _Bind``1(System.Object[])_.See also _Tags(System.Object[])_.
Field Unique
Unique tag.
Begins the definition of the binding.
```c#DI.Setup("Composition")
.Bind(Tag.Unique).To()
.Bind(Tag.Unique).To()
.Root>("Root");
```Field Type
Tag of target implementation type.
```c#DI.Setup("Composition")
.Bind(Tag.Type).To()
.Root("Root", typeof(Service));
```Method On(System.String[])
This tag allows you to determine which binding will be used for explicit injection for a particular injection site.
```c#DI.Setup("Composition")
.Bind(Tag.On("MyNamespace.Service.Service:dep"))
.To()
.Bind().To()
.Root("Root");
```- parameter _injectionSites_ - Set of labels for inection each, must be specified in a special format: ..[:argument]. The argument is specified only for the constructor and methods. The wildcards '*' and '?' are supported. All names are case-sensitive. The global namespace prefix 'global::' must be omitted.
Method OnConstructorArg``1(System.String)
This tag allows you to determine which binding will be used for explicit injection for a particular constructor argument.
```c#DI.Setup("Composition")
.Bind(Tag.OnConstructorArg("dep"))
.To()
.Bind().To()
.Root("Root");
```- parameter _argName_ - The name of the constructor argument.
Method OnMember``1(System.String)
This tag allows you to define which binding will be used for explicit injection for property or field of the type.
```c#DI.Setup("Composition")
.Bind(Tag.OnMember("DepProperty"))
.To()
.Bind().To()
.Root("Root");
```- parameter _memberName_ - The name of the type member.
Method OnMethodArg``1(System.String,System.String)
This tag allows you to determine which binding will be used for explicit injection for a particular method argument.
```c#DI.Setup("Composition")
.Bind(Tag.OnMethodArg("DoSomething", "state"))
.To()
.Bind().To()
.Root("Root");
```- parameter _methodName_ - The name of the type method.
- parameter _argName_ - The name of the method argument.
Field Overrider
Atomically generated smart tag with value "Overrider".
It's used for:
class _Generator__DependencyGraphBuilder_ <-- _IGraphRewriter_(Overrider) -- _GraphOverrider_ as _PerBlock_Field Cleaner
Atomically generated smart tag with value "Cleaner".
It's used for:
class _Generator__DependencyGraphBuilder_ <-- _IGraphRewriter_(Cleaner) -- _GraphCleaner_ as _PerBlock_Field CompositionClass
Atomically generated smart tag with value "CompositionClass".
It's used for:
class _Generator__CodeBuilder_ <-- _IBuilder`2_(CompositionClass) -- _CompositionClassBuilder_ as _PerBlock_Field UniqueTag
Atomically generated smart tag with value "UniqueTag".
It's used for:
class _Generator__ApiInvocationProcessor_ <-- (UniqueTag) -- _IdGenerator_ as _PerResolve_Field GenericType
Atomically generated smart tag with value "GenericType".
It's used for:
class _Generator__TypeResolver_ <-- _IIdGenerator_(GenericType) -- _IdGenerator_ as _PerResolve_Field UsingDeclarations
Atomically generated smart tag with value "UsingDeclarations".
It's used for:
class _Generator__CompositionClassBuilder_ <-- _IBuilder`2_(UsingDeclarations) -- _UsingDeclarationsBuilder_ as _PerBlock_Field Injection
Atomically generated smart tag with value "Injection".
Field Override
Atomically generated smart tag with value "Override".
It's used for:
class _Generator__OverrideIdProvider_ <-- _IIdGenerator_(Override) -- _IdGenerator_ as _PerResolve_TagAttribute
Represents a tag attribute overriding an injection tag. The tag can be a constant, a type, or a value of an enumerated type.
This attribute is part of the API, but you can use your own attribute at any time, and this allows you to define them in the assembly and namespace you want.
Sometimes it's important to take control of building a dependency graph. For example, when there are multiple implementations of the same contract. In this case, tags will help:
```c#interface IDependency { }
class AbcDependency : IDependency { }
class XyzDependency : IDependency { }
class Dependency : IDependency { }
interface IService
{
IDependency Dependency1 { get; }
IDependency Dependency2 { get; }
}
class Service : IService
{
public Service(
[Tag("Abc")] IDependency dependency1,
[Tag("Xyz")] IDependency dependency2)
{
Dependency1 = dependency1;
Dependency2 = dependency2;
}
public IDependency Dependency1 { get; }
public IDependency Dependency2 { get; }
}
DI.Setup("Composition")
.Bind("Abc").To()
.Bind("Xyz").To()
.Bind().To().Root("Root");
```See also _DependencyAttribute_.
See also _OrdinalAttribute_.
See also _TypeAttribute_.
Constructor TagAttribute(System.Object)
Creates an attribute instance.
- parameter _tag_ - The injection tag. See also _Tags(System.Object[])_
.
TT
Represents the generic type arguments marker for a reference type.
TT1
Represents the generic type arguments marker for a reference type.
TT2
Represents the generic type arguments marker for a reference type.
TT3
Represents the generic type arguments marker for a reference type.
TT4
Represents the generic type arguments marker for a reference type.
TTCollection`1
Represents the generic type arguments marker for _ICollection>T>_.
TTCollection1`1
Represents the generic type arguments marker for _ICollection>T>_.
TTCollection2`1
Represents the generic type arguments marker for _ICollection>T>_.
TTCollection3`1
Represents the generic type arguments marker for _ICollection>T>_.
TTCollection4`1
Represents the generic type arguments marker for _ICollection>T>_.
TTComparable
Represents the generic type arguments marker for _IComparable_.
TTComparable`1
Represents the generic type arguments marker for _IComparable>T>_.
TTComparable1
Represents the generic type arguments marker for _IComparable_.
TTComparable1`1
Represents the generic type arguments marker for _IComparable>T>_.
TTComparable2
Represents the generic type arguments marker for _IComparable_.
TTComparable2`1
Represents the generic type arguments marker for _IComparable>T>_.
TTComparable3
Represents the generic type arguments marker for _IComparable_.
TTComparable3`1
Represents the generic type arguments marker for _IComparable>T>_.
TTComparable4
Represents the generic type arguments marker for _IComparable_.
TTComparable4`1
Represents the generic type arguments marker for _IComparable>T>_.
TTComparer`1
Represents the generic type arguments marker for _IComparer>T>_.
TTComparer1`1
Represents the generic type arguments marker for _IComparer>T>_.
TTComparer2`1
Represents the generic type arguments marker for _IComparer>T>_.
TTComparer3`1
Represents the generic type arguments marker for _IComparer>T>_.
TTComparer4`1
Represents the generic type arguments marker for _IComparer>T>_.
TTDictionary`2
Represents the generic type arguments marker for _IDictionary>TKey, TValue>_.
TTDictionary1`2
Represents the generic type arguments marker for _IDictionary>TKey, TValue>_.
TTDictionary2`2
Represents the generic type arguments marker for _IDictionary>TKey, TValue>_.
TTDictionary3`2
Represents the generic type arguments marker for _IDictionary>TKey, TValue>_.
TTDictionary4`2
Represents the generic type arguments marker for _IDictionary>TKey, TValue>_.
TTDisposable
Represents the generic type arguments marker for _IDisposable_.
TTDisposable1
Represents the generic type arguments marker for _IDisposable_.
TTDisposable2
Represents the generic type arguments marker for _IDisposable_.
TTDisposable3
Represents the generic type arguments marker for _IDisposable_.
TTDisposable4
Represents the generic type arguments marker for _IDisposable_.
TTE
Represents the generic type arguments marker for a enum type.
TTE1
Represents the generic type arguments marker for a enum type.
TTE2
Represents the generic type arguments marker for a enum type.
TTE3
Represents the generic type arguments marker for a enum type.
TTE4
Represents the generic type arguments marker for a enum type.
TTEnumerable`1
Represents the generic type arguments marker for _IEnumerable>T>_.
TTEnumerable1`1
Represents the generic type arguments marker for _IEnumerable>T>_.
TTEnumerable2`1
Represents the generic type arguments marker for _IEnumerable>T>_.
TTEnumerable3`1
Represents the generic type arguments marker for _IEnumerable>T>_.
TTEnumerable4`1
Represents the generic type arguments marker for _IEnumerable>T>_.
TTEnumerator`1
Represents the generic type arguments marker for _IEnumerator>T>_.
TTEnumerator1`1
Represents the generic type arguments marker for _IEnumerator>T>_.
TTEnumerator2`1
Represents the generic type arguments marker for _IEnumerator>T>_.
TTEnumerator3`1
Represents the generic type arguments marker for _IEnumerator>T>_.
TTEnumerator4`1
Represents the generic type arguments marker for _IEnumerator>T>_.
TTEqualityComparer`1
Represents the generic type arguments marker for _IEqualityComparer>T>_.
TTEqualityComparer1`1
Represents the generic type arguments marker for _IEqualityComparer>T>_.
TTEqualityComparer2`1
Represents the generic type arguments marker for _IEqualityComparer>T>_.
TTEqualityComparer3`1
Represents the generic type arguments marker for _IEqualityComparer>T>_.
TTEqualityComparer4`1
Represents the generic type arguments marker for _IEqualityComparer>T>_.
TTEquatable`1
Represents the generic type arguments marker for _IEquatable>T>_.
TTEquatable1`1
Represents the generic type arguments marker for _IEquatable>T>_.
TTEquatable2`1
Represents the generic type arguments marker for _IEquatable>T>_.
TTEquatable3`1
Represents the generic type arguments marker for _IEquatable>T>_.
TTEquatable4`1
Represents the generic type arguments marker for _IEquatable>T>_.
TTList`1
Represents the generic type arguments marker for _IList>T>_.
TTList1`1
Represents the generic type arguments marker for _IList>T>_.
TTList2`1
Represents the generic type arguments marker for _IList>T>_.
TTList3`1
Represents the generic type arguments marker for _IList>T>_.
TTList4`1
Represents the generic type arguments marker for _IList>T>_.
TTObservable`1
Represents the generic type arguments marker for _IObservable>T>_.
TTObservable1`1
Represents the generic type arguments marker for _IObservable>T>_.
TTObservable2`1
Represents the generic type arguments marker for _IObservable>T>_.
TTObservable3`1
Represents the generic type arguments marker for _IObservable>T>_.
TTObservable4`1
Represents the generic type arguments marker for _IObservable>T>_.
TTObserver`1
Represents the generic type arguments marker for _IObserver>T>_.
TTObserver1`1
Represents the generic type arguments marker for _IObserver>T>_.
TTObserver2`1
Represents the generic type arguments marker for _IObserver>T>_.
TTObserver3`1
Represents the generic type arguments marker for _IObserver>T>_.
TTObserver4`1
Represents the generic type arguments marker for _IObserver>T>_.
TTReadOnlyCollection`1
Represents the generic type arguments marker for _IReadOnlyCollection>T>_.
TTReadOnlyCollection1`1
Represents the generic type arguments marker for _IReadOnlyCollection>T>_.
TTReadOnlyCollection2`1
Represents the generic type arguments marker for _IReadOnlyCollection>T>_.
TTReadOnlyCollection3`1
Represents the generic type arguments marker for _IReadOnlyCollection>T>_.
TTReadOnlyCollection4`1
Represents the generic type arguments marker for _IReadOnlyCollection>T>_.
TTReadOnlyList`1
Represents the generic type arguments marker for _IReadOnlyList>T>_.
TTReadOnlyList1`1
Represents the generic type arguments marker for _IReadOnlyList>T>_.
TTReadOnlyList2`1
Represents the generic type arguments marker for _IReadOnlyList>T>_.
TTReadOnlyList3`1
Represents the generic type arguments marker for _IReadOnlyList>T>_.
TTReadOnlyList4`1
Represents the generic type arguments marker for _IReadOnlyList>T>_.
TTS
Represents the generic type arguments marker for a value type.
TTS1
Represents the generic type arguments marker for a value type.
TTS2
Represents the generic type arguments marker for a value type.
TTS3
Represents the generic type arguments marker for a value type.
TTS4
Represents the generic type arguments marker for a value type.
TTSet`1
Represents the generic type arguments marker for _ISet>T>_.
TTSet1`1
Represents the generic type arguments marker for _ISet>T>_.
TTSet2`1
Represents the generic type arguments marker for _ISet>T>_.
TTSet3`1
Represents the generic type arguments marker for _ISet>T>_.
TTSet4`1
Represents the generic type arguments marker for _ISet>T>_.
TypeAttribute
The injection type can be defined manually using the `Type` attribute.This attribute explicitly overrides an injected type, otherwise it would be determined automatically based on the type of the constructor/method, property, or field parameter.
This attribute is part of the API, but you can use your own attribute at any time, and this allows you to define them in the assembly and namespace you want.
```c#interface IDependency { }
class AbcDependency : IDependency { }
class XyzDependency : IDependency { }
interface IService
{
IDependency Dependency1 { get; }
IDependency Dependency2 { get; }
}
class Service : IService
{
public Service(
[Type(typeof(AbcDependency))] IDependency dependency1,
[Type(typeof(XyzDependency))] IDependency dependency2)
{
Dependency1 = dependency1;
Dependency2 = dependency2;
}
public IDependency Dependency1 { get; }
public IDependency Dependency2 { get; }
}
DI.Setup("Composition")
.Bind().To().Root("Root");
```See also _DependencyAttribute_.
See also _TagAttribute_.
See also _OrdinalAttribute_.
Constructor TypeAttribute(System.Type)
Creates an attribute instance.
- parameter _type_ - The injection type. See also _Bind``1(System.Object[])_ and _Bind``1(System.Object[])_.## Examples
### Basics
- [Auto-bindings](readme/auto-bindings.md)
- [Injections of abstractions](readme/injections-of-abstractions.md)
- [Composition roots](readme/composition-roots.md)
- [Resolve methods](readme/resolve-methods.md)
- [Simplified binding](readme/simplified-binding.md)
- [Factory](readme/factory.md)
- [Simplified factory](readme/simplified-factory.md)
- [Injections as required](readme/injections-as-required.md)
- [Injections as required with arguments](readme/injections-as-required-with-arguments.md)
- [Class arguments](readme/class-arguments.md)
- [Root arguments](readme/root-arguments.md)
- [Tags](readme/tags.md)
- [Smart tags](readme/smart-tags.md)
- [Build up of an existing object](readme/build-up-of-an-existing-object.md)
- [Builder](readme/builder.md)
- [Builder with arguments](readme/builder-with-arguments.md)
- [Builders](readme/builders.md)
- [Builders with a name template](readme/builders-with-a-name-template.md)
- [Field injection](readme/field-injection.md)
- [Method injection](readme/method-injection.md)
- [Property injection](readme/property-injection.md)
- [Default values](readme/default-values.md)
- [Required properties or fields](readme/required-properties-or-fields.md)
- [Overrides](readme/overrides.md)
- [Root binding](readme/root-binding.md)
- [Async Root](readme/async-root.md)
- [Consumer types](readme/consumer-types.md)
- [Roots](readme/roots.md)
- [Roots with filter](readme/roots-with-filter.md)
### Lifetimes
- [Transient](readme/transient.md)
- [Singleton](readme/singleton.md)
- [PerResolve](readme/perresolve.md)
- [PerBlock](readme/perblock.md)
- [Scope](readme/scope.md)
- [Auto scoped](readme/auto-scoped.md)
- [Default lifetime](readme/default-lifetime.md)
- [Default lifetime for a type](readme/default-lifetime-for-a-type.md)
- [Default lifetime for a type and a tag](readme/default-lifetime-for-a-type-and-a-tag.md)
- [Disposable singleton](readme/disposable-singleton.md)
- [Async disposable singleton](readme/async-disposable-singleton.md)
- [Async disposable scope](readme/async-disposable-scope.md)
### Base Class Library
- [Func](readme/func.md)
- [Enumerable](readme/enumerable.md)
- [Enumerable generics](readme/enumerable-generics.md)
- [Array](readme/array.md)
- [Lazy](readme/lazy.md)
- [Task](readme/task.md)
- [ValueTask](readme/valuetask.md)
- [Manually started tasks](readme/manually-started-tasks.md)
- [Span and ReadOnlySpan](readme/span-and-readonlyspan.md)
- [Tuple](readme/tuple.md)
- [Weak Reference](readme/weak-reference.md)
- [Async Enumerable](readme/async-enumerable.md)
- [Service collection](readme/service-collection.md)
- [Func with arguments](readme/func-with-arguments.md)
- [Func with tag](readme/func-with-tag.md)
- [Keyed service provider](readme/keyed-service-provider.md)
- [Service provider](readme/service-provider.md)
- [Service provider with scope](readme/service-provider-with-scope.md)
- [Overriding the BCL binding](readme/overriding-the-bcl-binding.md)
### Generics
- [Generics](readme/generics.md)
- [Generic composition roots](readme/generic-composition-roots.md)
- [Complex generics](readme/complex-generics.md)
- [Generic composition roots with constraints](readme/generic-composition-roots-with-constraints.md)
- [Generic async composition roots with constraints](readme/generic-async-composition-roots-with-constraints.md)
- [Custom generic argument](readme/custom-generic-argument.md)
- [Build up of an existing generic object](readme/build-up-of-an-existing-generic-object.md)
- [Generic root arguments](readme/generic-root-arguments.md)
- [Complex generic root arguments](readme/complex-generic-root-arguments.md)
- [Generic builder](readme/generic-builder.md)
- [Generic builders](readme/generic-builders.md)
- [Generic roots](readme/generic-roots.md)
- [Generic injections as required](readme/generic-injections-as-required.md)
- [Generic injections as required with arguments](readme/generic-injections-as-required-with-arguments.md)
### Attributes
- [Constructor ordinal attribute](readme/constructor-ordinal-attribute.md)
- [Dependency attribute](readme/dependency-attribute.md)
- [Member ordinal attribute](readme/member-ordinal-attribute.md)
- [Tag attribute](readme/tag-attribute.md)
- [Type attribute](readme/type-attribute.md)
- [Inject attribute](readme/inject-attribute.md)
- [Custom attributes](readme/custom-attributes.md)
- [Custom universal attribute](readme/custom-universal-attribute.md)
- [Custom generic argument attribute](readme/custom-generic-argument-attribute.md)
- [Bind attribute](readme/bind-attribute.md)
- [Bind attribute with lifetime and tag](readme/bind-attribute-with-lifetime-and-tag.md)
- [Bind attribute for a generic type](readme/bind-attribute-for-a-generic-type.md)
### Interception
- [Decorator](readme/decorator.md)
- [Interception](readme/interception.md)
- [Advanced interception](readme/advanced-interception.md)
### Hints
- [Resolve hint](readme/resolve-hint.md)
- [ThreadSafe hint](readme/threadsafe-hint.md)
- [OnDependencyInjection regular expression hint](readme/ondependencyinjection-regular-expression-hint.md)
- [OnDependencyInjection wildcard hint](readme/ondependencyinjection-wildcard-hint.md)
- [OnCannotResolve regular expression hint](readme/oncannotresolve-regular-expression-hint.md)
- [OnCannotResolve wildcard hint](readme/oncannotresolve-wildcard-hint.md)
- [OnNewInstance regular expression hint](readme/onnewinstance-regular-expression-hint.md)
- [OnNewInstance wildcard hint](readme/onnewinstance-wildcard-hint.md)
- [ToString hint](readme/tostring-hint.md)
- [Check for a root](readme/check-for-a-root.md)
### Advanced
- [Composition root kinds](readme/composition-root-kinds.md)
- [Root with name template](readme/root-with-name-template.md)
- [Tag Type](readme/tag-type.md)
- [Tag Unique](readme/tag-unique.md)
- [Tag on injection site](readme/tag-on-injection-site.md)
- [Tag on a constructor argument](readme/tag-on-a-constructor-argument.md)
- [Tag on a member](readme/tag-on-a-member.md)
- [Tag on a method argument](readme/tag-on-a-method-argument.md)
- [Tag on injection site with wildcards](readme/tag-on-injection-site-with-wildcards.md)
- [Dependent compositions](readme/dependent-compositions.md)
- [Accumulators](readme/accumulators.md)
- [Global compositions](readme/global-compositions.md)
- [Partial class](readme/partial-class.md)
- [A few partial classes](readme/a-few-partial-classes.md)
- [Tracking disposable instances per a composition root](readme/tracking-disposable-instances-per-a-composition-root.md)
- [Tracking disposable instances in delegates](readme/tracking-disposable-instances-in-delegates.md)
- [Tracking disposable instances using pre-built classes](readme/tracking-disposable-instances-using-pre-built-classes.md)
- [Tracking disposable instances with different lifetimes](readme/tracking-disposable-instances-with-different-lifetimes.md)
- [Tracking async disposable instances per a composition root](readme/tracking-async-disposable-instances-per-a-composition-root.md)
- [Tracking async disposable instances in delegates](readme/tracking-async-disposable-instances-in-delegates.md)
- [Exposed roots](readme/exposed-roots.md)
- [Exposed roots with tags](readme/exposed-roots-with-tags.md)
- [Exposed roots via arg](readme/exposed-roots-via-arg.md)
- [Exposed roots via root arg](readme/exposed-roots-via-root-arg.md)
- [Exposed generic roots](readme/exposed-generic-roots.md)
- [Exposed generic roots with args](readme/exposed-generic-roots-with-args.md)
- [DI tracing via serilog](readme/di-tracing-via-serilog.md)
### Unity
- [Basic Unity use case](readme/basic-unity-use-case.md)
- [Unity MonoBehaviours](readme/unity-monobehaviours.md)
### Applications
- Console
- [Schrödinger's cat](readme/Console.md)
- [Top level statements](readme/ConsoleTopLevelStatements.md)
- [Native AOT](readme/ConsoleNativeAOT.md)
- [Unity](readme/Unity.md)
- UI
- [MAUI](readme/Maui.md)
- [WPF](readme/Wpf.md)
- [Avalonia](readme/Avalonia.md)
- [Win Forms Net Core](readme/WinFormsAppNetCore.md)
- [Win Forms](readme/WinFormsApp.md)
- Web
- [Web](readme/WebApp.md)
- [Minimal Web API](readme/MinimalWebAPI.md)
- [Web API](readme/WebAPI.md)
- [gRPC service](readme/GrpcService.md)
- [Blazor Server](readme/BlazorServerApp.md)
- [Blazor WebAssembly](readme/BlazorWebAssemblyApp.md)
- [https://devteam.github.io/Pure.DI/](https://devteam.github.io/Pure.DI/)
- Git repo with examples
- [Schrödinger's cat](https://github.com/DevTeam/Pure.DI.Example)
- [How to use Pure.DI to create and test libraries](https://github.com/DevTeam/Pure.DI.Solution)## Generated Code
Each generated class, hereafter called a _composition_, must be customized. Setup starts with a call to the `Setup(string compositionTypeName)` method:
```c#
DI.Setup("Composition")
.Bind().To()
.Bind().To()
.Root("Root");
```The following class will be generated
```c#
partial class Composition
{
// Default constructor
public Composition() { }// Scope constructor
internal Composition(Composition parentScope) { }// Composition root
public IService Root
{
get
{
return new Service(new Dependency());
}
}public T Resolve() { ... }
public T Resolve(object? tag) { ... }
public object Resolve(Type type) { ... }
public object Resolve(Type type, object? tag) { ... }
}
```The _compositionTypeName_ parameter can be omitted
- if the setup is performed inside a partial class, then the composition will be created for this partial class
- for the case of a class with composition kind `CompositionKind.Global`, see [this example](readme/global-compositions.md)Setup arguments
The first parameter is used to specify the name of the composition class. All sets with the same name will be combined to create one composition class. Alternatively, this name may contain a namespace, e.g. a composition class is generated for `Sample.Composition`:
```c#
namespace Sample
{
partial class Composition
{
...
}
}
```The second optional parameter may have multiple values to determine the kind of composition.
### CompositionKind.Public
This value is used by default. If this value is specified, a normal composition class will be created.
### CompositionKind.Internal
If you specify this value, the class will not be generated, but this setup can be used by others as a base setup. For example:
```c#
DI.Setup("BaseComposition", CompositionKind.Internal)
.Bind().To();DI.Setup("Composition").DependsOn("BaseComposition")
.Bind().To();
```If the _CompositionKind.Public_ flag is set in the composition setup, it can also be the base for other compositions, as in the example above.
### CompositionKind.Global
No composition class will be created when this value is specified, but this setup is the base setup for all setups in the current project, and `DependsOn(...)` is not required.
Constructors
### Default constructor
It's quite trivial, this constructor simply initializes the internal state.
### Parameterized constructor
It replaces the default constructor and is only created if at least one argument is specified. For example:
```c#
DI.Setup("Composition")
.Arg("name")
.Arg("id")
...
```In this case, the constructor with arguments is as follows:
```c#
public Composition(string name, int id) { ... }
```and there is no default constructor. It is important to remember that only those arguments that are used in the object graph will appear in the constructor. Arguments that are not involved cannot be defined, as they are omitted from the constructor parameters to save resources.
### Scope constructor
This constructor creates a composition instance for the new scope. This allows ``Lifetime.Scoped`` to be applied. See [this](readme/scope.md) example for details.
Composition Roots
### Public Composition Roots
To create an object graph quickly and conveniently, a set of properties (or a methods) is formed. These properties/methods are here called roots of compositions. The type of a property/method is the type of the root object created by the composition. Accordingly, each invocation of a property/method leads to the creation of a composition with a root element of this type.
```c#
DI.Setup("Composition")
.Bind().To()
.Root("MyService");
```In this case, the property for the _IService_ type will be named _MyService_ and will be available for direct use. The result of its use will be the creation of a composition of objects with the root of _IService_ type:
```c#
public IService MyService
{
get
{
...
return new Service(...);
}
}
```This is [recommended way](https://blog.ploeh.dk/2011/07/28/CompositionRoot/) to create a composition root. A composition class can contain any number of roots.
### Private Composition Roots
If the root name is empty, a private composition root with a random name is created:
```c#
private IService RootM07D16di_0001
{
get { ... }
}
```This root is available in _Resolve_ methods in the same way as public roots. For example:
```c#
DI.Setup("Composition")
.Bind().To()
.Root();
```These properties have an arbitrary name and access modifier _private_ and cannot be used directly from the code. Do not attempt to use them, as their names are arbitrarily changed. Private composition roots can be resolved by _Resolve_ methods.
Methods "Resolve"
### Methods "Resolve"
By default, a set of four _Resolve_ methods is generated:
```c#
public T Resolve() { ... }public T Resolve(object? tag) { ... }
public object Resolve(Type type) { ... }
public object Resolve(Type type, object? tag) { ... }
```These methods can resolve both public and private composition roots that do not depend on any arguments of the composition roots. They are useful when using the [Service Locator](https://martinfowler.com/articles/injection.html) approach, where the code resolves composition roots in place:
```c#
var composition = new Composition();composition.Resolve();
```This is a [not recommended](https://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/) way to create composition roots because _Resolve_ methods have a number of disadvantages:
- They provide access to an unlimited set of dependencies.
- Their use can potentially lead to runtime exceptions, for example, when the corresponding root has not been defined.
- Lead to performance degradation because they search for the root of a composition based on its type.To control the generation of these methods, see the [Resolve](#resolve-hint) hint.
### Dispose and DisposeAsync
Provides a mechanism to release unmanaged resources. These methods are generated only if the composition contains at least one singleton/scoped instance that implements either the [IDisposable](https://learn.microsoft.com/en-us/dotnet/api/system.idisposable) and/or [DisposeAsync](https://learn.microsoft.com/en-us/dotnet/api/system.iasyncdisposable.disposeasync) interface. The `Dispose()` or `DisposeAsync()` method of the composition should be called to dispose of all created singleton/scoped objects:
```c#
using var composition = new Composition();
```or
```c#
await using var composition = new Composition();
```To dispose objects of other lifetimes please see [this](readme/tracking-disposable-instances-per-a-composition-root.md) or [this](readme/tracking-disposable-instances-in-delegates.md) examples.
Setup hints
## Setup hints
Hints are used to fine-tune code generation. Setup hints can be used as shown in the following example:
```c#
DI.Setup("Composition")
.Hint(Hint.Resolve, "Off")
.Hint(Hint.ThreadSafe, "Off")
.Hint(Hint.ToString, "On")
...
```In addition, setup hints can be commented out before the _Setup_ method as `hint = value`. For example:
```c#
// Resolve = Off
// ThreadSafe = Off
DI.Setup("Composition")
...
```Both approaches can be mixed:
```c#
// Resolve = Off
DI.Setup("Composition")
.Hint(Hint.ThreadSafe, "Off")
...
```| Hint | Values | C# version | Default |
|------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------|------------|-----------|
| [Resolve](#resolve-hint) | _On_ or _Off_ | | _On_ |
| [OnNewInstance](#onnewinstance-hint) | _On_ or _Off_ | 9.0 | _Off_ |
| [OnNewInstancePartial](#onnewinstance-hint) | _On_ or _Off_ | | _On_ |
| [OnNewInstanceImplementationTypeNameRegularExpression](#onnewinstanceimplementationtypenameregularexpression-hint) | Regular expression | | .+ |
| [OnNewInstanceImplementationTypeNameWildcard](#onnewinstanceimplementationtypenamewildcard-hint) | Wildcard | | * |
| [OnNewInstanceTagRegularExpression](#onnewinstancetagregularexpression-hint) | Regular expression | | .+ |
| [OnNewInstanceTagWildcard](#onnewinstancetagwildcard-hint) | Wildcard | | * |
| [OnNewInstanceLifetimeRegularExpression](#onnewinstancelifetimeregularexpression-hint) | Regular expression | | .+ |
| [OnNewInstanceLifetimeWildcard](#onnewinstancelifetimewildcard-hint) | Wildcard | | * |
| [OnDependencyInjection](#ondependencyinjection-hint) | _On_ or _Off_ | 9.0 | _Off_ |
| [OnDependencyInjectionPartial](#ondependencyinjectionpartial-hint) | _On_ or _Off_ | | _On_ |
| [OnDependencyInjectionImplementationTypeNameRegularExpression](#OnDependencyInjectionImplementationTypeNameRegularExpression-Hint) | Regular expression | | .+ |
| [OnDependencyInjectionImplementationTypeNameWildcard](#OnDependencyInjectionImplementationTypeNameWildcard-Hint) | Wildcard | | * |
| [OnDependencyInjectionContractTypeNameRegularExpression](#ondependencyinjectioncontracttypenameregularexpression-hint) | Regular expression | | .+ |
| [OnDependencyInjectionContractTypeNameWildcard](#ondependencyinjectioncontracttypenameWildcard-hint) | Wildcard | | * |
| [OnDependencyInjectionTagRegularExpression](#ondependencyinjectiontagregularexpression-hint) | Regular expression | | .+ |
| [OnDependencyInjectionTagWildcard](#ondependencyinjectiontagWildcard-hint) | Wildcard | | * |
| [OnDependencyInjectionLifetimeRegularExpression](#ondependencyinjectionlifetimeregularexpression-hint) | Regular expression | | .+ |
| [OnDependencyInjectionLifetimeWildcard](#ondependencyinjectionlifetimeWildcard-hint) | Wildcard | | * |
| [OnCannotResolve](#oncannotresolve-hint) | _On_ or _Off_ | 9.0 | _Off_ |
| [OnCannotResolvePartial](#oncannotresolvepartial-hint) | _On_ or _Off_ | | _On_ |
| [OnCannotResolveContractTypeNameRegularExpression](#oncannotresolvecontracttypenameregularexpression-hint) | Regular expression | | .+ |
| [OnCannotResolveContractTypeNameWildcard](#oncannotresolvecontracttypenameцildcard-hint) | Wildcard | | * |
| [OnCannotResolveTagRegularExpression](#oncannotresolvetagregularexpression-hint) | Regular expression | | .+ |
| [OnCannotResolveTagWildcard](#oncannotresolvetagWildcard-hint) | Wildcard | | * |
| [OnCannotResolveLifetimeRegularExpression](#oncannotresolvelifetimeregularexpression-hint) | Regular expression | | .+ |
| [OnCannotResolveLifetimeWildcard](#oncannotresolvelifetimeWildcard-hint) | Wildcard | | * |
| [OnNewRoot](#onnewroot-hint) | _On_ or _Off_ | | _Off_ |
| [OnNewRootPartial](#onnewrootpartial-hint) | _On_ or _Off_ | | _On_ |
| [ToString](#tostring-hint) | _On_ or _Off_ | | _Off_ |
| [ThreadSafe](#threadsafe-hint) | _On_ or _Off_ | | _On_ |
| [ResolveMethodModifiers](#resolvemethodmodifiers-hint) | Method modifier | | _public_ |
| [ResolveMethodName](#resolvemethodname-hint) | Method name | | _Resolve_ |
| [ResolveByTagMethodModifiers](#resolvebytagmethodmodifiers-hint) | Method modifier | | _public_ |
| [ResolveByTagMethodName](#resolvebytagmethodname-hint) | Method name | | _Resolve_ |
| [ObjectResolveMethodModifiers](#objectresolvemethodmodifiers-hint) | Method modifier | | _public_ |
| [ObjectResolveMethodName](#objectresolvemethodname-hint) | Method name | | _Resolve_ |
| [ObjectResolveByTagMethodModifiers](#objectresolvebytagmethodmodifiers-hint) | Method modifier | | _public_ |
| [ObjectResolveByTagMethodName](#objectresolvebytagmethodname-hint) | Method name | | _Resolve_ |
| [DisposeMethodModifiers](#disposemethodmodifiers-hint) | Method modifier | | _public_ |
| [DisposeAsyncMethodModifiers](#disposeasyncmethodmodifiers-hint) | Method modifier | | _public_ |
| [FormatCode](#formatcode-hint) | _On_ or _Off_ | | _Off_ |
| [SeverityOfNotImplementedContract](#severityofnotimplementedcontract-hint) | _Error_ or _Warning_ or _Info_ or _Hidden_ | | _Error_ |
| [Comments](#comments-hint) | _On_ or _Off_ | | _On_ |
| [SystemThreadingLock](#systemthreadinglock-hint) | _On_ or _Off_ | | _On_ |The list of hints will be gradually expanded to meet the needs and desires for fine-tuning code generation. Please feel free to add your ideas.
### Resolve Hint
Determines whether to generate [_Resolve_ methods](#resolve). By default, a set of four _Resolve_ methods are generated. Set this hint to _Off_ to disable the generation of resolve methods. This will reduce the generation time of the class composition, and in this case no [private composition roots](#private-composition-roots) will be generated. The class composition will be smaller and will only have [public roots](#public-composition-roots). When the _Resolve_ hint is disabled, only the public roots properties are available, so be sure to explicitly define them using the `Root(string name)` method with an explicit composition root name.
### OnNewInstance Hint
Determines whether to use the _OnNewInstance_ partial method. By default, this partial method is not generated. This can be useful, for example, for logging purposes:
```c#
internal partial class Composition
{
partial void OnNewInstance(ref T value, object? tag, object lifetime) =>
Console.WriteLine($"'{typeof(T)}'('{tag}') created.");
}
```You can also replace the created instance with a `T` type, where `T` is the actual type of the created instance. To minimize performance loss when calling _OnNewInstance_, use the three hints below.
### OnNewInstancePartial Hint
Determines whether to generate the _OnNewInstance_ partial method. By default, this partial method is generated when the _OnNewInstance_ hint is ```On```.
### OnNewInstanceImplementationTypeNameRegularExpression Hint
This is a regular expression for filtering by instance type name. This hint is useful when _OnNewInstance_ is in _On_ state and it is necessary to limit the set of types for which the _OnNewInstance_ method will be called.
### OnNewInstanceImplementationTypeNameWildcard Hint
This is a Wildcard for filtering by instance type name. This hint is useful when _OnNewInstance_ is in _On_ state and it is necessary to limit the set of types for which the _OnNewInstance_ method will be called.
### OnNewInstanceTagRegularExpression Hint
This is a regular expression for filtering by _tag_. This hint is also useful when _OnNewInstance_ is in _On_ state and it is necessary to limit the set of _tags_ for which the _OnNewInstance_ method will be called.
### OnNewInstanceTagWildcard Hint
This is a wildcard for filtering by _tag_. This hint is also useful when _OnNewInstance_ is in _On_ state and it is necessary to limit the set of _tags_ for which the _OnNewInstance_ method will be called.
### OnNewInstanceLifetimeRegularExpression Hint
This is a regular expression for filtering by _lifetime_. This hint is also useful when _OnNewInstance_ is in _On_ state and it is necessary to restrict the set of _life_ times for which the _OnNewInstance_ method will be called.
### OnNewInstanceLifetimeWildcard Hint
This is a wildcard for filtering by _lifetime_. This hint is also useful when _OnNewInstance_ is in _On_ state and it is necessary to restrict the set of _life_ times for which the _OnNewInstance_ method will be called.
### OnDependencyInjection Hint
Determines whether to use the _OnDependencyInjection_ partial method when the _OnDependencyInjection_ hint is ```On``` to control dependency injection. By default it is ```On```.
```c#
// OnDependencyInjection = On
// OnDependencyInjectionPartial = Off
// OnDependencyInjectionContractTypeNameRegularExpression = ICalculator[\d]{1}
// OnDependencyInjectionTagRegularExpression = Abc
DI.Setup("Composition")
...
```### OnDependencyInjectionPartial Hint
Determines whether to generate the _OnDependencyInjection_ partial method to control dependency injection. By default, this partial method is not generated. It cannot have an empty body because of the return value. It must be overridden when it is generated. This may be useful, for example, for [Interception Scenario](readme/interception.md).
```c#
// OnDependencyInjection = On
// OnDependencyInjectionContractTypeNameRegularExpression = ICalculator[\d]{1}
// OnDependencyInjectionTagRegularExpression = Abc
DI.Setup("Composition")
...
```To minimize performance loss when calling _OnDependencyInjection_, use the three tips below.
### OnDependencyInjectionImplementationTypeNameRegularExpression Hint
This is a regular expression for filtering by instance type name. This hint is useful when _OnDependencyInjection_ is in _On_ state and it is necessary to restrict the set of types for which the _OnDependencyInjection_ method will be called.
### OnDependencyInjectionImplementationTypeNameWildcard Hint
This is a wildcard for filtering by instance type name. This hint is useful when _OnDependencyInjection_ is in _On_ state and it is necessary to restrict the set of types for which the _OnDependencyInjection_ method will be called.
### OnDependencyInjectionContractTypeNameRegularExpression Hint
This is a regular expression for filtering by the name of the resolving type. This hint is also useful when _OnDependencyInjection_ is in _On_ state and it is necessary to limit the set of permissive types for which the _OnDependencyInjection_ method will be called.
### OnDependencyInjectionContractTypeNameWildcard Hint
This is a wildcard for filtering by the name of the resolving type. This hint is also useful when _OnDependencyInjection_ is in _On_ state and it is necessary to limit the set of permissive types for which the _OnDependencyInjection_ method will be called.
### OnDependencyInjectionTagRegularExpression Hint
This is a regular expression for filtering by _tag_. This hint is also useful when _OnDependencyInjection_ is in the _On_ state and you want to limit the set of _tags_ for which the _OnDependencyInjection_ method will be called.
### OnDependencyInjectionTagWildcard Hint
This is a wildcard for filtering by _tag_. This hint is also useful when _OnDependencyInjection_ is in the _On_ state and you want to limit the set of _tags_ for which the _OnDependencyInjection_ method will be called.
### OnDependencyInjectionLifetimeRegularExpression Hint
This is a regular expression for filtering by _lifetime_. This hint is also useful when _OnDependencyInjection_ is in _On_ state and it is necessary to restrict the set of _lifetime_ for which the _OnDependencyInjection_ method will be called.
### OnDependencyInjectionLifetimeWildcard Hint
This is a wildcard for filtering by _lifetime_. This hint is also useful when _OnDependencyInjection_ is in _On_ state and it is necessary to restrict the set of _lifetime_ for which the _OnDependencyInjection_ method will be called.
### OnCannotResolve Hint
Determines whether to use the `OnCannotResolve(...)` partial method to handle a scenario in which an instance cannot be resolved. By default, this partial method is not generated. Because of the return value, it cannot have an empty body and must be overridden at creation.
```c#
// OnCannotResolve = On
// OnCannotResolveContractTypeNameRegularExpression = string|DateTime
// OnDependencyInjectionTagRegularExpression = null
DI.Setup("Composition")
...
```To avoid missing failed bindings by mistake, use the two relevant hints below.
### OnCannotResolvePartial Hint
Determines whether to generate the `OnCannotResolve(...)` partial method when the _OnCannotResolve_ hint is On to handle a scenario in which an instance cannot be resolved. By default it is ```On```.
```c#
// OnCannotResolve = On
// OnCannotResolvePartial = Off
// OnCannotResolveContractTypeNameRegularExpression = string|DateTime
// OnDependencyInjectionTagRegularExpression = null
DI.Setup("Composition")
...
```To avoid missing failed bindings by mistake, use the two relevant hints below.
### OnNewRoot Hint
Determines whether to use a static partial method `OnNewRoot(...)` to handle the new composition root registration event.
```c#
// OnNewRoot = On
DI.Setup("Composition")
...
```Be careful, this hint disables checks for the ability to resolve dependencies!
### OnNewRootPartial Hint
Determines whether to generate a static partial method `OnNewRoot(...)` when the _OnNewRoot_ hint is ```On``` to handle the new composition root registration event.
```c#
// OnNewRootPartial = Off
DI.Setup("Composition")
...
```### OnCannotResolveContractTypeNameRegularExpression Hint
This is a regular expression for filtering by the name of the resolving type. This hint is also useful when _OnCannotResolve_ is in _On_ state and it is necessary to limit the set of resolving types for which the _OnCannotResolve_ method will be called.
### OnCannotResolveContractTypeNameWildcard Hint
This is a wildcard for filtering by the name of the resolving type. This hint is also useful when _OnCannotResolve_ is in _On_ state and it is necessary to limit the set of resolving types for which the _OnCannotResolve_ method will be called.
### OnCannotResolveTagRegularExpression Hint
This is a regular expression for filtering by _tag_. This hint is also useful when _OnCannotResolve_ is in _On_ state and it is necessary to limit the set of _tags_ for which the _OnCannotResolve_ method will be called.
### OnCannotResolveTagWildcard Hint
This is a wildcard for filtering by _tag_. This hint is also useful when _OnCannotResolve_ is in _On_ state and it is necessary to limit the set of _tags_ for which the _OnCannotResolve_ method will be called.
### OnCannotResolveLifetimeRegularExpression Hint
This is a regular expression for filtering by _lifetime_. This hint is also useful when _OnCannotResolve_ is in the _On_ state and it is necessary to restrict the set of _lives_ for which the _OnCannotResolve_ method will be called.
### OnCannotResolveLifetimeWildcard Hint
This is a wildcard for filtering by _lifetime_. This hint is also useful when _OnCannotResolve_ is in the _On_ state and it is necessary to restrict the set of _lives_ for which the _OnCannotResolve_ method will be called.
### ToString Hint
Determines whether to generate the _ToString()_ method. This method provides a class diagram in [mermaid](https://mermaid.js.org/) format. To see this diagram, just call the ToString method and copy the text to [this site](https://mermaid.live/).
```c#
// ToString = On
DI.Setup("Composition")
.Bind().To()
.Root("MyService");
var composition = new Composition();
string classDiagram = composition.ToString();
```### ThreadSafe Hint
This hint determines whether the composition of objects will be created in a thread-safe way. The default value of this hint is _On_. It is a good practice not to use threads when creating an object graph, in this case the hint can be disabled, which will result in a small performance gain. For example:
```c#
// ThreadSafe = Off
DI.Setup("Composition")
.Bind().To()
.Root("MyService");
```### ResolveMethodModifiers Hint
Overrides the modifiers of the `public T Resolve()` method.
### ResolveMethodName Hint
Overrides the method name for `public T Resolve()`.
### ResolveByTagMethodModifiers Hint
Overrides the modifiers of the `public T Resolve(object? tag)` method.
### ResolveByTagMethodName Hint
Overrides the method name for `public T Resolve(object? tag)`.
### ObjectResolveMethodModifiers Hint
Overrides the modifiers of the `public object Resolve(Type type)` method.
### ObjectResolveMethodName Hint
Overrides the method name for `public object Resolve(Type type)`.
### ObjectResolveByTagMethodModifiers Hint
Overrides the modifiers of the `public object Resolve(Type type, object? tag)` method.
### ObjectResolveByTagMethodName Hint
Overrides the method name for `public object Resolve(Type type, object? tag)`.
### DisposeMethodModifiers Hint
Overrides the modifiers of the `public void Dispose()` method.
### DisposeAsyncMethodModifiers Hint
Overrides the modifiers of the `public ValueTask DisposeAsync()` method.
### FormatCode Hint
Specifies whether the generated code should be formatted. This option consumes a lot of CPU resources. This hint may be useful when studying the generated code or, for example, when making presentations.
### SeverityOfNotImplementedContract Hint
Indicates the severity level of the situation when, in the binding, an implementation does not implement a contract. Possible values:
- _"Error"_, it is default value.
- _"Warning"_ - something suspicious but allowed.
- _"Info"_ - information that does not indicate a problem.
- _"Hidden"_ - what's not a problem.### Comments Hint
Specifies whether the generated code should be commented.
```c#
// Represents the composition class
DI.Setup(nameof(Composition))
.Bind().To()
// Provides a composition root of my service
.Root("MyService");
```Appropriate comments will be added to the generated ```Composition``` class and the documentation for the class, depending on the IDE used, will look something like this:
### SystemThreadingLock Hint
Indicates whether `System.Threading.Lock` should be used whenever possible instead of the classic approach of synchronizing object access using `System.Threading.Monitor1. `On` by default.
```c#
DI.Setup(nameof(Composition))
.Hint(Hint.SystemThreadingLock, "Off")
.Bind().To()
.Root("MyService");
```
Then documentation for the composition root:

Code generation workflow
```mermaid
flowchart TD
start@{ shape: circle, label: "Start" }
setups[fa:fa-search DI setups analysis]
types["`fa:fa-search Types analysis
constructors/methods/properties/fields`"]
subgraph dep[Dependency graph]
option[fa:fa-search Selecting a next dependency set]
creating[fa:fa-cog Creating a dependency graph variant]
verification{fa:fa-check-circle Verification}
end
codeGeneration[fa:fa-code Code generation]
compilation[fa:fa-cog Compilation]
failed@{ shape: dbl-circ, label: "fa:fa-thumbs-down Compilation failed" }
success@{ shape: dbl-circ, label: "fa:fa-thumbs-up Success" }start ==> setups
setups -.->|Has problems| failed
setups ==> types
types -.-> |Has problems| failed
types ==> option
option ==> creating
option -.-> |There are no other options| failed
creating ==> verification
verification -->|Has problems| option
verification ==>|Correct| codeGeneration
codeGeneration ==> compilation
compilation -.-> |Has problems| failed
compilation ==> success
```## Project template
Install the DI template [Pure.DI.Templates](https://www.nuget.org/packages/Pure.DI.Templates)
```shell
dotnet new install Pure.DI.Templates
```Create a "Sample" console application from the template *__di__*
```shell
dotnet new di -o ./Sample
```And run it
```shell
dotnet run --project Sample
```For more information about the template, please see [this page](https://github.com/DevTeam/Pure.DI/wiki/Project-templates).
## Troubleshooting
Version update
When updating the version, it is possible that the previous version of the code generator remains active and is used by compilation services. In this case, the old and new versions of the generator may conflict. For a project where the code generator is used, it is recommended to do the following:
- After updating the version, close the IDE if it is open
- Delete the _obj_ and _bin_ directories
- Execute the following commands one by one```shell
dotnet build-server shutdown
``````shell
dotnet restore
``````shell
dotnet build
```Disabling API generation
Pure.DI automatically generates its API. If an assembly already has the Pure.DI API, for example, from another assembly, it is sometimes necessary to disable its automatic generation to avoid ambiguity. To do this, you need to add a _DefineConstants_ element to the project files of these modules. For example:
```xml
$(DefineConstants);PUREDI_API_SUPPRESSION
```
Display generated files
You can set project properties to save generated files and control their storage location. In the project file, add the `` element to the `` group and set its value to `true`. Build the project again. The generated files are now created in the _obj/Debug/netX.X/generated/Pure.DI/Pure.DI/Pure.DI.SourceGenerator_ directory. The path components correspond to the build configuration, the target framework, the source generator project name, and the full name of the generator type. You can choose a more convenient output folder by adding the `` element to the application project file. For example:
```xml
true
$(BaseIntermediateOutputPath)Generated
```
Performance profiling
Please install the [JetBrains.dotTrace.GlobalTools](https://www.nuget.org/packages/JetBrains.dotTrace.GlobalTools) dotnet tool globally, for example:
```shell
dotnet tool install --global JetBrains.dotTrace.GlobalTools --version 2024.3.3
```Or make sure it is installed. Add the following sections to the project:
```xml
c:\profiling
```
Replace the path like *c:\profiling* with the path where the profiling results will be saved.
Start the project build and wait until a file like *c:\profiling\pure_di_????.dtt* appears in the directory.
## Additional resources
Examples of how to set up a composition
- [Pure.DI](https://github.com/DevTeam/Pure.DI/blob/master/src/Pure.DI.Core/Generator.cs)
- [C# interactive](https://github.com/DevTeam/csharp-interactive/blob/master/CSharpInteractive/Composition.cs)
- [Immutype](https://github.com/DevTeam/Immutype/blob/master/Immutype/Composition.cs)
- [MSBuild logger](https://github.com/JetBrains/teamcity-msbuild-logger/blob/master/TeamCity.MSBuild.Logger/Composition.cs)Articles
- [RU New in Pure.DI by the end of 2024](https://habr.com/ru/articles/868744/)
- [RU New in Pure.DI](https://habr.com/ru/articles/808297/)
- [RU Pure.DI v2.1](https://habr.com/ru/articles/795809/)
- [RU Pure.DI next step](https://habr.com/ru/articles/554236/)
- [RU Pure.DI for .NET](https://habr.com/ru/articles/552858/)RU DotNext video
## AI Context
Contextual AI needs to understand the situation it’s in. This means knowing details like API, usage scenarios, etc. This helps the AI give more relevant and personalized responses. So Markdown docs below can be useful if you or your team rely on an AI assistant to write code using Pure.DI:
| AI Context file | Size | Tokens |
| --------------- | ---- | ------ |
| [AI_CONTEXT_SMALL.md](AI_CONTEXT_SMALL.md) | 27KB | 7K |
| [AI_CONTEXT_MEDIUM.md](AI_CONTEXT_MEDIUM.md) | 123KB | 31K |
| [AI_CONTEXT_LARGE.md](AI_CONTEXT_LARGE.md) | 377KB | 96K |
## How to contribute to Pure.DIThank you for your interest in contributing to the Pure.DI project! First of all, if you are going to make a big change or feature, please open a problem first. That way, we can coordinate and understand if the change you're going to work on fits with current priorities and if we can commit to reviewing and merging it within a reasonable timeframe. We don't want you to waste a lot of your valuable time on something that may not align with what we want for Pure.DI.
Contribution prerequisites: [.NET SDK 9.0](https://dotnet.microsoft.com/en-us/download/dotnet/9.0) or later is installed.
This repository contains the following directories and files:
```
📁 .github GitHub related files and main.yml for building using GitGub actions
📁 .logs temporary files for generating the README.md file
📁 .run configuration files for the Rider IDE
📁 benchmarks projects for performance measurement
📁 build application for building locally and using CI/CD
📁 docs resources for the README.md file
📁 readme sample scripts and examples of application implementations
📁 samples sample projects
📁 src source codes of the code generator and all libraries
|- 📂 Pure.DI source code generator project
|- 📂 Pure.DI.Abstractions abstraction library for Pure.DI
|- 📂 Pure.DI.Core basic implementation of the source code generator
|- 📂 Pure.DI.MS project for integration with Microsoft DI
|- 📂 Pure.DI.Templates project templates for creating .NET projects using Pure.DI
|- 📄 Directory.Build.props common MSBUILD properties for all source code generator projects
|- 📄 Library.props common MSBUILD properties for library projects such as Pure.DI.Abstractions
📁 tests contains projects for testing
|- 📂 Pure.DI.Example project for testing some integration scenarios
|- 📂 Pure.DI.IntegrationTests integration tests
|- 📂 Pure.DI.Tests unit tests for basic functionality
|- 📂 Pure.DI.UsageTests usage tests, used for examples in README.md
|- 📄 Directory.Build.props common MSBUILD properties for all test projects
📄 LICENSE license file
📄 build.cmd Windows script file to run one of the build steps, see description below
📄 build.sh Linux/Mac OS script file to run one of the build steps, see description below
📄 .space.kts build file using JetBrains space actions
📄 README.md this README.md file
📄 SECURITY.md policy file for handling security bugs and vulnerabilities
📄 Directory.Build.props basic MSBUILD properties for all projects
📄 Pure.DI.sln .NET solution file
```The entire build logic is a regular [console .NET application](/build). You can use the [build.cmd](/build.cmd) and [build.sh](/build.sh) files with the appropriate command in the parameters to perform all basic actions on the project, e.g:
| Commands | Description |
|----------|-------------|
| ai, ai | Generate AI context |
| bm, benchmarks, benchmarks | Run benchmarks |
| c, check, check | Compatibility checks |
| dp, deploy, deploy | Package deployment |
| e, example, example | Create examples |
| g, generator, generator | Build and test the source code generator |
| i, install, install | Install templates |
| l, libs, libs | Build and test libraries |
| p, pack, pack | Create NuGet packages |
| perf, performance, performance | Performance tests |
| pb, publish, publish | Publish the balazor web sssembly example |
| r, readme, readme | Generate README.md |
| t, template, template | Create and deploy templates |
| te, testexamples, testexamples | Test examples |
| u, upgrade, upgrade | Upgrading the internal version of DI to the latest public version |For example, to build and test the source code generator:
```shell
./build.sh generator
```or to run benchmarks:
```shell
./build.cmd benchmarks
```If you are using the Rider IDE, it already has a set of configurations to run these commands. This project uses [C# interactive](https://github.com/DevTeam/csharp-interactive) build automation system for .NET. This tool helps to make .NET builds more efficient.

### State of build
| Tests | Examples | Performance |
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [/statusIcon)](https://teamcity.jetbrains.com/viewType.html?buildTypeId=OpenSourceProjects_DevTeam_PureDi_BuildAndTestBuildType&guest=1) | [/statusIcon)](https://teamcity.jetbrains.com/viewType.html?buildTypeId=OpenSourceProjects_DevTeam_PureDi_TestExamples&guest=1) | [/statusIcon)](https://teamcity.jetbrains.com/viewType.html?buildTypeId=OpenSourceProjects_DevTeam_PureDi_PerformanceTests&guest=1) |Thanks!
## Benchmarks
Array
Method Mean ErrorStdDevMedianRatioRatioSDGen0Gen1AllocatedAlloc Ratio
'Pure.DI composition root'88.33 ns1.075 ns1.006 ns88.58 ns0.940.030.0377-632 B1.00
'Pure.DI Resolve<T>()'91.94 ns1.832 ns2.445 ns91.66 ns0.980.040.0377-632 B1.00
'Pure.DI Resolve(Type)'92.65 ns2.244 ns6.366 ns89.18 ns0.980.070.0377-632 B1.00
'Hand Coded'94.24 ns1.883 ns2.578 ns94.06 ns1.000.040.0377-632 B1.00
DryIoc99.10 ns0.999 ns0.834 ns98.91 ns1.050.030.0377-632 B1.00
LightInject103.24 ns2.119 ns4.183 ns102.65 ns1.100.050.0377-632 B1.00
Unity4,510.09 ns74.628 ns66.155 ns4,488.31 ns47.891.470.86210.007614520 B22.97
Autofac15,134.66 ns110.608 ns86.355 ns15,131.24 ns160.724.451.70900.061028976 B45.85[Array details](readme/ArrayDetails.md)
Enum
Method Mean ErrorStdDevMedianRatioRatioSDGen0Gen1AllocatedAlloc Ratio
'Pure.DI composition root'64.36 ns1.282 ns2.919 ns62.75 ns1.000.050.0205-344 B1.00
'Hand Coded'64.49 ns0.791 ns0.661 ns64.47 ns1.000.010.0205-344 B1.00
'Pure.DI Resolve<T>()'65.26 ns0.965 ns0.903 ns65.56 ns1.010.020.0205-344 B1.00
'Pure.DI Resolve(Type)'65.43 ns1.004 ns0.784 ns65.23 ns1.010.020.0205-344 B1.00
'Microsoft DI'93.40 ns1.322 ns1.172 ns92.96 ns1.450.020.0281-472 B1.37
LightInject147.58 ns1.650 ns1.544 ns147.96 ns2.290.030.0510-856 B2.49
DryIoc147.61 ns1.110 ns0.984 ns147.54 ns2.290.030.0510-856 B2.49
Unity3,736.48 ns73.272 ns68.539 ns3,739.88 ns57.941.180.82020.007613752 B39.98
Autofac15,610.79 ns288.580 ns595.967 ns15,436.50 ns242.089.471.73950.061029104 B84.60[Enum details](readme/EnumDetails.md)
Func
Method Mean ErrorStdDevRatioRatioSDGen0Gen1AllocatedAlloc Ratio
'Pure.DI composition root'4.382 ns0.0561 ns0.0525 ns0.840.010.0014-24 B1.00
'Hand Coded'5.193 ns0.0649 ns0.0542 ns1.000.010.0014-24 B1.00
'Pure.DI Resolve<T>()'5.914 ns0.0753 ns0.0667 ns1.140.020.0014-24 B1.00
'Pure.DI Resolve(Type)'6.375 ns0.0465 ns0.0388 ns1.230.010.0014-24 B1.00
DryIoc28.979 ns0.3875 ns0.3435 ns5.580.080.0072-120 B5.00
LightInject155.185 ns2.9628 ns2.7714 ns29.890.600.0300-504 B21.00
Unity1,760.400 ns12.4774 ns11.6714 ns339.033.990.1507-2552 B106.33
Autofac5,745.474 ns36.1642 ns30.1988 ns1,106.5112.280.83160.007614008 B583.67[Func details](readme/FuncDetails.md)
Singleton
Method Mean Error StdDevRatioRatioSDGen0Gen1AllocatedAlloc Ratio
'Hand Coded'3.016 ns0.0721 ns0.0602 ns1.000.030.0014-24 B1.00
'Pure.DI composition root'3.337 ns0.0778 ns0.0728 ns1.110.030.0014-24 B1.00
'Pure.DI Resolve<T>()'3.517 ns0.0602 ns0.0533 ns1.170.030.0014-24 B1.00
'Pure.DI Resolve(Type)'4.649 ns0.1417 ns0.3832 ns1.540.130.0014-24 B1.00
DryIoc11.388 ns0.0389 ns0.0304 ns3.780.070.0014-24 B1.00
'Simple Injector'16.630 ns0.0782 ns0.0693 ns5.520.110.0014-24 B1.00
'Microsoft DI'19.551 ns0.0684 ns0.0606 ns6.490.120.0014-24 B1.00
LightInject426.861 ns1.0945 ns0.9702 ns141.592.700.0014-24 B1.00
Unity2,645.530 ns47.7345 ns66.9171 ns877.5127.400.1869-3184 B132.67
Autofac9,723.452 ns60.9124 ns53.9972 ns3,225.2463.411.43430.045824208 B1,008.67
'Castle Windsor'16,991.331 ns93.5701 ns87.5255 ns5,635.97110.231.4038-23912 B996.33
Ninject67,297.995 ns1,045.7465 ns927.0271 ns22,322.54516.334.27251.098673176 B3,049.00[Singleton details](readme/SingletonDetails.md)
Transient
Method Mean Error StdDev RatioRatioSDGen0Gen1AllocatedAlloc Ratio
'Pure.DI composition root'3.491 ns0.1203 ns0.2764 ns0.970.090.0014-24 B1.00
'Hand Coded'3.619 ns0.1132 ns0.1952 ns1.000.070.0014-24 B1.00
'Pure.DI Resolve<T>()'4.417 ns0.1377 ns0.3429 ns1.220.110.0014-24 B1.00
'Pure.DI Resolve(Type)'4.649 ns0.1431 ns0.1338 ns1.290.080.0014-24 B1.00
LightInject7.043 ns0.0902 ns0.0754 ns1.950.100.0014-24 B1.00
'Microsoft DI'10.357 ns0.1357 ns0.1133 ns2.870.150.0014-24 B1.00
DryIoc10.673 ns0.1197 ns0.1119 ns2.960.160.0014-24 B1.00
'Simple Injector'14.594 ns0.1373 ns0.1217 ns4.040.210.0014-24 B1.00
Unity4,320.577 ns85.0619 ns175.6675 ns1,197.1378.580.3052-5176 B215.67
Autofac12,616.111 ns227.4971 ns201.6703 ns3,495.62189.021.98360.091633224 B1,384.33
'Castle Windsor'27,766.858 ns312.7020 ns277.2021 ns7,693.52405.543.23490.030554360 B2,265.00
Ninject148,286.554 ns3,309.2559 ns9,600.7521 ns41,086.583,398.597.56841.4648128736 B5,364.00[Transient details](readme/TransientDetails.md)
Benchmarks environment
BenchmarkDotNet v0.14.0, Windows 10 (10.0.19045.4894/22H2/2022Update)
AMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores
.NET SDK 9.0.100
[Host] : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2
DefaultJob : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2