Created
November 6, 2015 21:14
-
-
Save nanoninja/45df97849aa2c0de552c to your computer and use it in GitHub Desktop.
ServiceContainer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2015 The Nanoninja Authors. All rights reserved. | |
package container | |
// ServiceFunc registers the service function. | |
type ServiceFunc func(c *container) interface{} | |
type container struct { | |
name string | |
services map[string]interface{} | |
} | |
// New allocates a new service container with the given name. | |
func New(name string) *container { | |
return &container{name, make(map[string]interface{})} | |
} | |
// Name returns the name of the container. | |
func (c container) Name() string { | |
return c.name | |
} | |
func (c *container) Set(key string, val ServiceFunc) { | |
c.services[key] = val | |
} | |
func (c container) Get(key string) interface{} { | |
if service, ok := c.services[key]; ok { | |
return service.(ServiceFunc)(&c) | |
} | |
return nil | |
} | |
func (c container) Share(s ServiceFunc) ServiceFunc { | |
var service interface{} | |
return func(c *container) interface{} { | |
if service == nil { | |
service = s(c) | |
} | |
return service | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment