feat: WithName for explicit service naming
Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
parent
b03c1a3a3c
commit
001e90ed13
2 changed files with 31 additions and 0 deletions
18
contract.go
18
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(
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue