Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,14 @@ Immutable collection of capabilities attached to a subject. Thread-safe.
| Method | Returns | Description |
|--------|---------|-------------|
| `GetAll<TCapability>()` | `IReadOnlyList<TCapability>` | Retrieves all capabilities of the specified type in order |
| `GetFirstOrDefault<TCapability>()` | `TCapability?` | Gets the first capability of the specified type, or null if none exists |
| `GetRequiredFirst<TCapability>()` | `TCapability` | Gets the first capability of the specified type (throws if not found) |
| `TryGetFirst<TCapability>(out TCapability capability)` | `bool` | Tries to get the first capability of the specified type |
| `GetLastOrDefault<TCapability>()` | `TCapability?` | Gets the last capability of the specified type, or null if none exists |
| `GetRequiredLast<TCapability>()` | `TCapability` | Gets the last capability of the specified type (throws if not found) |
| `TryGetLast<TCapability>(out TCapability capability)` | `bool` | Tries to get the last capability of the specified type |
| `Has<TCapability>()` | `bool` | Checks if any capability of the specified type exists |
| `Count<TCapability>()` | `int` | Gets the count of capabilities of the specified type |

### Primary Capability Methods

Expand All @@ -160,6 +167,8 @@ Immutable collection of capabilities attached to a subject. Thread-safe.
|--------|-----------|-----------|
| `GetPrimary()` | `InvalidOperationException` | If no primary capability exists |
| `GetRequiredPrimaryAs<T>()` | `InvalidOperationException` | If primary capability doesn't exist or isn't of the specified type |
| `GetRequiredFirst<T>()` | `InvalidOperationException` | If no capability of the specified type exists |
| `GetRequiredLast<T>()` | `InvalidOperationException` | If no capability of the specified type exists |

### Example

Expand All @@ -168,6 +177,19 @@ Immutable collection of capabilities attached to a subject. Thread-safe.
var validators = composition.GetAll<IValidator>();
var hasLogging = composition.Has<ILogger>();

// Get first capability (convenient when you expect only one)
var config = composition.GetFirstOrDefault<ConfigCapability>();
if (config != null)
{
// Use config
}

// Or use Try pattern
if (composition.TryGetFirst<ConfigCapability>(out var cfg))
{
// Use cfg
}

// Work with primary
if (composition.TryGetPrimary(out var primary))
{
Expand Down
57 changes: 57 additions & 0 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,63 @@ if (composition.Has<PrintCapability>())
{
Console.WriteLine("Document can be printed");
}

// Get first capability (convenient when you expect only one)
var printCap = composition.GetFirstOrDefault<PrintCapability>();
if (printCap != null)
{
printCap.Print(document);
}
```

### Getting Single Capabilities

When you know there's only one capability of a type, use `GetFirstOrDefault` or `TryGetFirst`:

```csharp
var composition = scope.For(application)
.Add(new ConfigurationCapability("appsettings.json"))
.Add(new LoggingCapability("app.log"))
.Build();

// GetFirstOrDefault returns null if not found
var config = composition.GetFirstOrDefault<ConfigurationCapability>();
if (config != null)
{
var setting = config.GetSetting("Key");
}

// TryGetFirst uses out parameter pattern
if (composition.TryGetFirst<LoggingCapability>(out var logger))
{
logger.Log("Application started");
}

// GetRequiredFirst throws if not found (useful when capability is mandatory)
try
{
var cache = composition.GetRequiredFirst<CacheCapability>();
cache.Store("key", value);
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Required capability not found: {ex.Message}");
}

// GetLast methods - useful for "override" or "last wins" scenarios
var overrideConfig = composition.GetLastOrDefault<ConfigOverrideCapability>();
if (overrideConfig != null)
{
// Use the last registered override (highest priority)
ApplyConfig(overrideConfig);
}

// TryGetLast with out parameter
if (composition.TryGetLast<ThemeCapability>(out var theme))
{
// Apply the most recently added theme
ApplyTheme(theme);
}
```

### Working with Multiple Capabilities of Same Type
Expand Down
241 changes: 241 additions & 0 deletions src/Cocoar.Capabilities.Tests/GetFirstTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
using Xunit;

namespace Cocoar.Capabilities.Tests;

public class GetFirstTests
{
[Fact]
public void GetFirstOrDefault_WithNoCapabilities_ReturnsNull()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject).Build();

var result = composition.GetFirstOrDefault<TestCapability>();

Assert.Null(result);
}

[Fact]
public void GetFirstOrDefault_WithOneCapability_ReturnsThatCapability()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var capability = new TestCapability("First");
var composition = scope.For(subject)
.Add(capability)
.Build();

var result = composition.GetFirstOrDefault<TestCapability>();

Assert.NotNull(result);
Assert.Same(capability, result);
Assert.Equal("First", result.Name);
}

[Fact]
public void GetFirstOrDefault_WithMultipleCapabilities_ReturnsFirstInOrder()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject)
.Add(new TestCapability("Third"), order: 30)
.Add(new TestCapability("First"), order: 10)
.Add(new TestCapability("Second"), order: 20)
.Build();

var result = composition.GetFirstOrDefault<TestCapability>();

Assert.NotNull(result);
Assert.Equal("First", result!.Name);
}

[Fact]
public void TryGetFirst_WithNoCapabilities_ReturnsFalse()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject).Build();

var found = composition.TryGetFirst<TestCapability>(out var result);

Assert.False(found);
Assert.Null(result);
}

[Fact]
public void TryGetFirst_WithOneCapability_ReturnsTrueAndCapability()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var capability = new TestCapability("Only");
var composition = scope.For(subject)
.Add(capability)
.Build();

var found = composition.TryGetFirst<TestCapability>(out var result);

Assert.True(found);
Assert.NotNull(result);
Assert.Same(capability, result);
Assert.Equal("Only", result.Name);
}

[Fact]
public void TryGetFirst_WithMultipleCapabilities_ReturnsTrueAndFirstInOrder()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject)
.Add(new TestCapability("C"), order: 3)
.Add(new TestCapability("A"), order: 1)
.Add(new TestCapability("B"), order: 2)
.Build();

var found = composition.TryGetFirst<TestCapability>(out var result);

Assert.True(found);
Assert.NotNull(result);
Assert.Equal("A", result!.Name);
}

[Fact]
public void GetFirstOrDefault_WithDifferentTypes_ReturnsCorrectType()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject)
.Add(new TestCapability("TestCap"))
.Add(new DocumentCapability("DocType", "Content"))
.Build();

var testResult = composition.GetFirstOrDefault<TestCapability>();
var docResult = composition.GetFirstOrDefault<DocumentCapability>();

Assert.NotNull(testResult);
Assert.Equal("TestCap", testResult!.Name);

Assert.NotNull(docResult);
Assert.Equal("DocType", docResult!.Type);
}

[Fact]
public void TryGetFirst_WithRegistry_WorksCorrectly()
{
var options = new CapabilityScopeOptions
{
UseCompositionRegistry = true
};
using var scope = new CapabilityScope(options);
var subject = new StringSubject("registry-test");

var composition = scope.For(subject, useRegistry: true)
.Add(new TestCapability("First"))
.Add(new TestCapability("Second"))
.Build(useRegistry: true);

var retrieved = scope.Compositions.FindOrDefault(subject);
Assert.NotNull(retrieved);

var found = retrieved!.TryGetFirst<TestCapability>(out var result);

Assert.True(found);
Assert.Equal("First", result!.Name);
}

[Fact]
public void GetFirstOrDefault_WithNoOrderSpecified_ReturnsFirstAdded()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject)
.Add(new TestCapability("FirstAdded"))
.Add(new TestCapability("SecondAdded"))
.Add(new TestCapability("ThirdAdded"))
.Build();

var result = composition.GetFirstOrDefault<TestCapability>();

Assert.NotNull(result);
Assert.Equal("FirstAdded", result!.Name);
}

[Fact]
public void GetRequiredFirst_WithNoCapabilities_ThrowsInvalidOperationException()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject).Build();

var ex = Assert.Throws<InvalidOperationException>(() =>
composition.GetRequiredFirst<TestCapability>());

Assert.Contains("Capability of type 'TestCapability' not found", ex.Message);
}

[Fact]
public void GetRequiredFirst_WithOneCapability_ReturnsThatCapability()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var capability = new TestCapability("Required");
var composition = scope.For(subject)
.Add(capability)
.Build();

var result = composition.GetRequiredFirst<TestCapability>();

Assert.NotNull(result);
Assert.Same(capability, result);
Assert.Equal("Required", result.Name);
}

[Fact]
public void GetRequiredFirst_WithMultipleCapabilities_ReturnsFirstInOrder()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject)
.Add(new TestCapability("Z"), order: 30)
.Add(new TestCapability("A"), order: 10)
.Add(new TestCapability("M"), order: 20)
.Build();

var result = composition.GetRequiredFirst<TestCapability>();

Assert.NotNull(result);
Assert.Equal("A", result.Name);
}

[Fact]
public void GetRequiredFirst_WithDifferentTypes_ReturnsCorrectType()
{
using var scope = new CapabilityScope(TestOptions.Disabled);
var subject = new StringSubject("test");

var composition = scope.For(subject)
.Add(new TestCapability("TestCap"))
.Add(new DocumentCapability("DocType", "Content"))
.Build();

var testResult = composition.GetRequiredFirst<TestCapability>();
var docResult = composition.GetRequiredFirst<DocumentCapability>();

Assert.NotNull(testResult);
Assert.Equal("TestCap", testResult.Name);

Assert.NotNull(docResult);
Assert.Equal("DocType", docResult.Type);
}
}
Loading
Loading