英文:
dependency injection in grpc server go
问题
假设我们有一个包含gRPC服务器实现的Go API。
这个gRPC服务器方法需要执行各种任务,这些任务需要作为同一API中的不同服务进行抽象。
有没有一种方法可以将这个新服务注入到gRPC服务器中?
示例代码:
package grpcserver
func (g *GrpcServer) GrpcServerExample(ctx context.Context, r *grpcpackage.SampleGrpcRequest) (*grpcpackage.SampleGrpcResponse, error) {
service := differentService{} // 如何在这里注入而不是在这里创建
result := service.DoSomething()
return nil, nil
}
英文:
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
}
答案1
得分: 3
你可以在注册gRPC服务器时将服务注入到GrpcServer
中。
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{
// 在这里注入
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
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论