Introducing providers

The documentation defines a provider as follows:

"A function that can produce a value."

For our purposes, we can put it a different way—a provider returns an instance of a dependency. 

The simplest form a provider can take is a simple no argument function, as shown in the following code:

// Provider
func
ProvideFetcher() *Fetcher {
return &Fetcher{}
}

// Object being "provided"
type Fetcher struct {
}

func (f *Fetcher) GoFetch() (string, error) {

return "", errors.New("not implemented yet")
}

Providers can also indicate that they require dependencies to be injected by having parameters like this:

func ProvideFetcher(cache *Cache) *Fetcher {
return &Fetcher{
cache: cache,
}
}

The dependencies (parameters) of this provider must be provided by other providers.

Providers can also indicate that they may fail to initialize by returning an error, as shown in the following code:

func ProvideCache() (*Cache, error) {
cache := &Cache{}

err := cache.Start()
if err != nil {
return nil, err
}

return cache, nil
}

It is important to note that when a provider returns an error, any injector that uses the dependency provided must also return an error.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.151.164