feat: WithName for explicit service naming

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Snider 2026-03-24 20:06:56 +00:00
parent b03c1a3a3c
commit 001e90ed13
2 changed files with 31 additions and 0 deletions

View file

@ -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(

View file

@ -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) {