Dependency Injection
This package contains all of the fundamental functionalities for dependency injection (DI).
A ServiceProvider
can be used to register services and consume them in your application.
Features
This package provides the following features:
- Register services with a single instance (singleton only) or with a function (factory);
- Use of generic function to get your desired service;
- Three service lifetimes: singleton, scoped, transient;
- Async initialization (coming soon)
Service Lifetimes
A service can have the following lifetimes:
Transient
- a new instance is created every time it is requestedSingleton
- a single, new instance is created the first time it is requestedScoped
- a new instance is created once per ServiceScope the first time it is requested
Scope Scenarios
There scenarios where a service needs to be scoped; for example, for the lifetime of a HTTP request. A service definitely shouldn't live for the life of the application (e.g. singleton
), but it also shouldn't be created each time it's requested within the request (e.g. transient
). A scoped service lives for the lifetime of the container (ServiceScope
) it was created from.
Installation
go get github.com/fairking/di_plus
Usage
package main
import (
"github.com/fairking/di_plus"
)
type MySettingsService struct {
Connection string
}
type MyDatabaseService struct {
Settings MyDatabaseService
}
services := NewServiceBuilder().
Register(
GetTypeOf[MySettingsService](),
ServiceTypeEnum.Singleton,
func(s IServiceProvider) (interface{}, error) {
return MySettingsService{Connection: "server=127.0.0.1;uid=root;pwd=12345;database=test"}, nil
},
).
Register(
GetTypeOf[MyDatabaseService](),
ServiceTypeEnum.Scoped,
func(s IServiceProvider) (interface{}, error) {
return MyDatabaseService{Settings: GetService[*MySettingsService](s)}, nil
},
).
Build()
settings := services.GetService("MySettingsService").(*MySettingsService)
settings2 := GetService[*MySettingsService](services)
{
scope := services.GetScope()
db := GetService[*MyDatabaseService](scope)
db_, err := GetServiceOr[*MyDatabaseService](scope)
settings3 := GetService[*MySettingsService](services)
}
{
scope := services.GetScope()
db2 := GetService[*MyDatabaseService](scope)
db2_, err := GetServiceOr[*MyDatabaseService](scope)
settings3 := GetService[*MySettingsService](services)
}
Contribution
If you have questions please create a new issue.
Donations
Donate with Ӿ nano crypto (XNO).
Thank you!