Skip to content

Latest commit

 

History

History
121 lines (100 loc) · 2.9 KB

File metadata and controls

121 lines (100 loc) · 2.9 KB

Overriding the BCL binding

At any time, the default binding to the BCL type can be changed to your own:

using Shouldly;
using Pure.DI;

DI.Setup(nameof(Composition))
    .Bind<IMessageSender[]>().To<IMessageSender[]>(() =>
        [new EmailSender(), new SmsSender(), new EmailSender()]
    )
    .Bind<INotificationService>().To<NotificationService>()

    // Composition root
    .Root<INotificationService>("NotificationService");

var composition = new Composition();
var notificationService = composition.NotificationService;
notificationService.Senders.Length.ShouldBe(3);
notificationService.Senders[0].ShouldBeOfType<EmailSender>();
notificationService.Senders[1].ShouldBeOfType<SmsSender>();
notificationService.Senders[2].ShouldBeOfType<EmailSender>();

interface IMessageSender;

class EmailSender : IMessageSender;

class SmsSender : IMessageSender;

interface INotificationService
{
    IMessageSender[] Senders { get; }
}

class NotificationService(IMessageSender[] senders) : INotificationService
{
    public IMessageSender[] Senders { get; } = senders;
}
Running this code sample locally
dotnet --list-sdk
  • Create a net10.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

Note

Overriding BCL bindings allows you to provide custom implementations for standard types, enabling specialized behavior for your application.

The following partial class will be generated:

partial class Composition
{
  public INotificationService NotificationService
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      IMessageSender[] transient427 = [new EmailSender(), new SmsSender(), new EmailSender()];
      return new NotificationService(transient427);
    }
  }
}

Class diagram:

---
 config:
  maxTextSize: 2147483647
  maxEdges: 2147483647
  class:
   hideEmptyMembersBox: true
---
classDiagram
	NotificationService --|> INotificationService
	Composition ..> NotificationService : INotificationService NotificationService
	NotificationService *--  ArrayᐸIMessageSenderᐳ : ArrayᐸIMessageSenderᐳ
	class ArrayᐸIMessageSenderᐳ {
			<<array>>
	}
	namespace Pure.DI.UsageTests.BCL.OverridingBclBindingScenario {
		class Composition {
		<<partial>>
		+INotificationService NotificationService
		}
		class INotificationService {
			<<interface>>
		}
		class NotificationService {
				<<class>>
			+NotificationService(ArrayᐸIMessageSenderᐳ senders)
		}
	}
Loading