Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add close method #56

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,35 @@ func (c Container) Reset() {
}
}

// Close Calls the close method on all singleton instances within the container.
func (c Container) Close() error {
for _, abstraction := range c {
for _, concrete := range abstraction {
if !concrete.isSingleton {
continue
}
instance, err := concrete.make(c)
if err != nil {
return err
}

v := reflect.ValueOf(instance)
mm := v.MethodByName("Close")
if mm.IsValid() {
res := mm.Call(nil)
if len(res) > 0 {
errVal := res[0]
if errVal.Type().Name() == "error" && errVal.Interface() != nil {
err, _ := errVal.Interface().(error)
return err
}
}
}
}
}
return nil
}

// Singleton binds an abstraction to concrete in singleton mode.
// It takes a resolver function that returns the concrete, and its return type matches the abstraction (interface).
// The resolver function can have arguments of abstraction that have been declared in the Container already.
Expand Down
5 changes: 5 additions & 0 deletions global.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ func Reset() {
Global.Reset()
}

// Close calls the same method of the global concrete.
func Close() error {
return Global.Close()
}

// Call calls the same method of the global concrete.
func Call(receiver interface{}) error {
return Global.Call(receiver)
Expand Down