Skip to content

Instantly share code, notes, and snippets.

@khash
Created July 9, 2020 10:18
Show Gist options
  • Save khash/c17dd8bcac3e7f8afff59c62c74bff2a to your computer and use it in GitHub Desktop.
Save khash/c17dd8bcac3e7f8afff59c62c74bff2a to your computer and use it in GitHub Desktop.
A simple template for a IoC in Golang
package utils
import (
"context"
"errors"
"fmt"
"sync"
)
type ObjectID string
var (
// Put your Object IDs here if you want
// IPProvider = ObjectID("ip-provider")
)
type IoCContainer struct {
sync.RWMutex
objects map[ObjectID]interface{}
}
var (
Container = &IoCContainer{
objects: make(map[ObjectID]interface{}),
}
)
func (c *IoCContainer) Fetch(ctx context.Context, name ObjectID) interface{} {
c.RLock()
defer c.RUnlock()
if c.objects[name] == nil {
panic(fmt.Sprintf("no object named %s found in the container", name))
}
obj := c.objects[name]
return obj
}
func (c *IoCContainer) Assign(ctx context.Context, name ObjectID, obj interface{}) error {
c.Lock()
defer c.Unlock()
if c.objects[name] != nil {
return errors.New("object already exists with the same name")
}
c.objects[name] = obj
return nil
}
func (c *IoCContainer) Clear(ctx context.Context) {
c.Lock()
defer c.Unlock()
c.objects = make(map[ObjectID]interface{})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment