Suppose we have a go api containing a grpc server implementation.
This grpc server method has to do a variety of tasks which needs to be abstracted as a different service within the same api.
Is there a way to inject this new service in the grpc server?
Sample code:
package grpcserver
func (g *GrpcServer) GrpcServerExample(ctx context.Context, r *grpcpackage.SampleGrpcRequest) (*grpcpackage.SampleGrpcResponse, error) {
service := differentService{} //how to inject this instead of creating here
result := service.DoSomething()
return nil,nil
}
You can inject the service into GrpcServer
while registering the gRPC server.
package grpcserver
type GrpcServer struct {
MyService Service
}
func (g *GrpcServer) GrpcServerExample(ctx context.Context, r *grpcpackage.SampleGrpcRequest) (*grpcpackage.SampleGrpcResponse, error) {
service := g.MyService
result := service.DoSomething()
return nil,nil
}
func main() {
s := grpcpackage.NewServer()
grpcpackage.RegisterGrpcServer(s, &GrpcServer{
// Inject Here
MyService: &ServiceImpl{},
})
}
service_interface.go
package grpcserver
type Service interface {
DoSomething() int
}
service_impl.go
package grpcserver
type ServiceImpl struct {
}
func (s *ServiceImpl) DoSomething() int {
return 123
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.