using Shouldly;
using Pure.DI;
DI.Setup(nameof(Composition))
// Registers custom generic argument
.GenericTypeArgumentAttribute<MyGenericTypeArgumentAttribute>()
.Bind<IDependency<TTMy>>().To<Dependency<TTMy>>()
.Bind<IService>().To<Service>()
// Composition root
.Root<IService>("Root");
var composition = new Composition();
var service = composition.Root;
service.IntDependency.ShouldBeOfType<Dependency<int>>();
service.StringDependency.ShouldBeOfType<Dependency<string>>();
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
class MyGenericTypeArgumentAttribute : Attribute;
[MyGenericTypeArgument]
interface TTMy;
interface IDependency<T>;
class Dependency<T> : IDependency<T>;
interface IService
{
IDependency<int> IntDependency { get; }
IDependency<string> StringDependency { get; }
}
class Service(
IDependency<int> intDependency,
IDependency<string> stringDependency)
: IService
{
public IDependency<int> IntDependency { get; } = intDependency;
public IDependency<string> StringDependency { get; } = stringDependency;
}
Running this code sample locally
- Make sure you have the .NET SDK 9.0 or later is installed
dotnet --list-sdk
- Create a net9.0 (or later) console application
dotnet new console -n Sample
dotnet add package Pure.DI
dotnet add package Shouldly
- Copy the example code into the Program.cs file
You are ready to run the example 🚀
dotnet run
The following partial class will be generated:
partial class Composition
{
private readonly Composition _root;
[OrdinalAttribute(256)]
public Composition()
{
_root = this;
}
internal Composition(Composition parentScope)
{
_root = (parentScope ?? throw new ArgumentNullException(nameof(parentScope)))._root;
}
public IService Root
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return new Service(new Dependency<int>(), new Dependency<string>());
}
}
}
Class diagram:
---
config:
class:
hideEmptyMembersBox: true
---
classDiagram
Service --|> IService
DependencyᐸInt32ᐳ --|> IDependencyᐸInt32ᐳ
DependencyᐸStringᐳ --|> IDependencyᐸStringᐳ
Composition ..> Service : IService Root
Service *-- DependencyᐸInt32ᐳ : IDependencyᐸInt32ᐳ
Service *-- DependencyᐸStringᐳ : IDependencyᐸStringᐳ
namespace Pure.DI.UsageTests.Attributes.CustomGenericArgumentAttributeScenario {
class Composition {
<<partial>>
+IService Root
}
class DependencyᐸInt32ᐳ {
+Dependency()
}
class DependencyᐸStringᐳ {
+Dependency()
}
class IDependencyᐸInt32ᐳ {
<<interface>>
}
class IDependencyᐸStringᐳ {
<<interface>>
}
class IService {
<<interface>>
}
class Service {
+Service(IDependencyᐸInt32ᐳ intDependency, IDependencyᐸStringᐳ stringDependency)
}
}