From 001e90ed13f3e03471343b48bb0f1c83e9a34845 Mon Sep 17 00:00:00 2001 From: Snider Date: Tue, 24 Mar 2026 20:06:56 +0000 Subject: [PATCH] feat: WithName for explicit service naming Co-Authored-By: Virgil --- contract.go | 18 ++++++++++++++++++ contract_test.go | 13 +++++++++++++ 2 files changed, 31 insertions(+) diff --git a/contract.go b/contract.go index 6abb0fb..357d1de 100644 --- a/contract.go +++ b/contract.go @@ -178,6 +178,24 @@ func WithService(factory func(*Core) Result) CoreOption { } } +// WithName registers a service with an explicit name (no reflect discovery). +// +// core.WithName("ws", func(c *Core) Result { +// return Result{Value: hub, OK: true} +// }) +func WithName(name string, factory func(*Core) Result) CoreOption { + return func(c *Core) Result { + r := factory(c) + if !r.OK { + return r + } + if r.Value == nil { + return Result{E("core.WithName", Sprintf("failed to create service %q", name), nil), false} + } + return c.RegisterService(name, r.Value) + } +} + // WithOption is a convenience for setting a single key-value option. // // core.New( diff --git a/contract_test.go b/contract_test.go index 2186cff..c6a5317 100644 --- a/contract_test.go +++ b/contract_test.go @@ -59,6 +59,19 @@ func TestWithService_FactorySelfRegisters_Good(t *testing.T) { assert.True(t, svc.OK, "expected self-registered service to be present") } +// --- WithName --- + +func TestWithName_Good(t *testing.T) { + r := New( + WithName("custom", func(c *Core) Result { + return Result{Value: &stubNamedService{}, OK: true} + }), + ) + assert.True(t, r.OK) + c := r.Value.(*Core) + assert.Contains(t, c.Services(), "custom") +} + // TestWithService_FactoryError_Bad verifies that a factory returning an error // causes New() to stop and propagate the failure. func TestWithService_FactoryError_Bad(t *testing.T) {