Skip to content

Latest commit

 

History

History
108 lines (89 loc) · 2.37 KB

File metadata and controls

108 lines (89 loc) · 2.37 KB

Root with name template

Demonstrates how to use name templates for composition roots, allowing dynamic generation of root names based on patterns or parameters.

using Shouldly;
using Pure.DI;

DI.Setup("Composition")
    // The name template "My{type}" specifies that the root property name
    // will be formed by adding the prefix "My" to the type name "ApiClient".
    .Root<ApiClient>("My{type}");

var composition = new Composition();

// The property name is "MyApiClient" instead of "ApiClient"
// thanks to the name template "My{type}"
var apiClient = composition.MyApiClient;

apiClient.GetProfile().ShouldBe("Content from https://example.com/profile");

class NetworkClient
{
    public string Get(string uri) => $"Content from {uri}";
}

class ApiClient(NetworkClient client)
{
    public string GetProfile() => client.Get("https://example.com/profile");
}
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

Name templates provide flexibility in root naming but should be used consistently to maintain code readability.

The following partial class will be generated:

partial class Composition
{
  public ApiClient MyApiClient
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      return new ApiClient(new NetworkClient());
    }
  }
}

Class diagram:

---
 config:
  maxTextSize: 2147483647
  maxEdges: 2147483647
  class:
   hideEmptyMembersBox: true
---
classDiagram
	Composition ..> ApiClient : ApiClient MyApiClient
	ApiClient *--  NetworkClient : NetworkClient
	namespace Pure.DI.UsageTests.Advanced.RootWithNameTemplateScenario {
		class ApiClient {
				<<class>>
			+ApiClient(NetworkClient client)
		}
		class Composition {
		<<partial>>
		+ApiClient MyApiClient
		}
		class NetworkClient {
				<<class>>
			+NetworkClient()
		}
	}
Loading