Created
March 19, 2023 17:24
-
-
Save lmllrjr/8de0c66af52c5af3431da22a9c38f190 to your computer and use it in GitHub Desktop.
Dependency injection go
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
// 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