Created
November 23, 2018 02:58
-
-
Save kalysr/eae17b18b2fb655b31ecdff2d04c7941 to your computer and use it in GitHub Desktop.
("go.uber.org/dig") Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package di | |
import ( | |
"----/db" | |
"----/graph" | |
"----/routes" | |
"go.uber.org/dig" | |
"gopkg.in/mgo.v2" | |
) | |
var Container *dig.Container | |
func ConnectDatabase(config *Config) *mgo.Session { | |
session, err := mgo.Dial(config.DatabaseUri) | |
if err != nil { | |
panic("DB connection error") | |
} | |
return session | |
} | |
func NewServer(config *Config, authC *routes.Auth, mainC *routes.MainController, graphqlServer *graph.GraphqlServer) *Server { | |
return &Server{ | |
config: config, | |
authController: authC, | |
mainController: mainC, | |
GraphqlServer: graphqlServer, | |
} | |
} | |
func AuthController(models *db.ModelManager) *routes.Auth { | |
return &routes.Auth{ | |
Models: models, | |
} | |
} | |
func MainController(models *db.ModelManager) *routes.MainController { | |
return &routes.MainController{ | |
Models: models, | |
} | |
} | |
func ModelManager(config *Config, session *mgo.Session) *db.ModelManager { | |
return &db.ModelManager{Session: session, DataBase: config.Database} | |
} | |
func BuildContainer() *dig.Container { | |
Container := dig.New() | |
Container.Provide(NewConfig) | |
Container.Provide(ConnectDatabase) | |
Container.Provide(ModelManager) | |
Container.Provide(AuthController) | |
Container.Provide(MainController) | |
Container.Provide(graph.NewGraphqlServer) | |
Container.Provide(NewServer) | |
return Container | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
container := di.BuildContainer() | |
err := container.Invoke(func(server *di.Server) { | |
server.Run() | |
}) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to test it?