goioc

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2017 License: Apache-2.0 Imports: 2 Imported by: 7

README

GoIoC Build Status

GoIoC introduces inversion of control (IoC) to Go by providing a basic type registry.

Registering a New Type

The first step to using GoIoC is registering a new type:

type reader struct {
}

func (r *reader) Read(data []byte) (int, error) {
	return 0, nil
}

func main() {
	// Register a new type "reader" and a func() interface{} that
	// returns a new instance of the reader struct.
	goioc.Register("reader", func() interface{} { return &reader{} })
}

The GoIoC type registry now has a type named "reader" that can be recalled at anytime. Please note, however, that subsequent calls to Register will override existing types with the same name.

Constructing a Registered Type

The New function is used to construct a new instance of a registered type:

func main() {
	// Construct a new instance of the registered type "reader",
	// assert that it conforms to the io.Reader interface, and
	// then read some of its data into the data buffer.
	r := goioc.New("reader").(io.Reader)
	data := make([]byte, 1024)
	r.Read(data)
}

Request Types that Implement an Interface

GoIoC even makes it simple to request new instances of all types that implement a specific interface:

func main() {
	// Print the type name of all the registered types that implement
	// io.Reader. The code below will print *main.reader.
	for o := range goioc.Implements((*io.Reader)(nil)) {
		fmt.Printf("%T\n", o)
	}
}

Documentation

Overview

Package goioc provides a basic type registry for Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Implements

func Implements(ifaceObj interface{}) chan interface{}

Implements returns a channel that receives instantiated instances of all the registered types that implement the provided interface.

For example, imagine all objects that implement the io.Reader interface should be returned:

Implements((*io.Reader)(nil))

The above call will return instantiated objects for all registered types that implement the io.Reader interface.

func New

func New(name string) interface{}

New returns a new instance of the specified type name. If the specified type name is not found then a nil value is returned.

func Register

func Register(name string, ctor func() interface{})

Register registers a new type with a name and function that returns a new instance of the type.

If Register is called with a name that is already registered, the old registration will be overridden.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL