Skip to content

Instantly share code, notes, and snippets.

@lmllrjr
Created March 19, 2023 17:24
Show Gist options
  • Save lmllrjr/8de0c66af52c5af3431da22a9c38f190 to your computer and use it in GitHub Desktop.
Save lmllrjr/8de0c66af52c5af3431da22a9c38f190 to your computer and use it in GitHub Desktop.
Dependency injection go
// You can edit this code!
// Click here and start typing.
package main
import "fmt"
func main() {
msgRepo := Message{
MSG: "Hello there friends",
}
hwRepo := HelloWorldMessage{}
c := MyServiceConfig{
MessageRepo: msgRepo,
HelloWorldRepo: hwRepo,
}
s := NewMyService(c)
fmt.Println(s.Hello())
fmt.Println(s.HelloWorld())
}
type Service interface {
MessageRepository
HelloWorldRepository
}
type MessageRepository interface {
Hello() string
}
type Message struct {
MSG string
}
func (m Message) Hello() string {
return m.MSG
}
type HelloWorldRepository interface {
HelloWorld() string
}
type HelloWorldMessage struct{}
func (h HelloWorldMessage) HelloWorld() string {
return "hello world"
}
type myService struct {
messageRepo MessageRepository
helloWorldRepo HelloWorldRepository
}
type MyServiceConfig struct {
MessageRepo MessageRepository
HelloWorldRepo HelloWorldRepository
}
func (s *myService) Hello() string {
return s.messageRepo.Hello()
}
func (s *myService) HelloWorld() string {
return s.helloWorldRepo.HelloWorld()
}
var _ Service = (*myService)(nil)
func NewMyService(c MyServiceConfig) Service {
var svc Service
svc = &myService{
messageRepo: c.MessageRepo,
helloWorldRepo: c.HelloWorldRepo,
}
return svc
}
func (s *myService) Do() error {
fmt.Printf("%T", s)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment