gRPC服务器中的依赖注入(Dependency Injection)

huangapple go评论81阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2016年12月12日 20:12:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41100683.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定