Skip to content

UseCase & Dependency Injection

The einar-cli enables you to generate custom business use cases by automatically generating the necessary files and imports for managing your business logic.

👨‍💻 Generate a New UseCase

Inside your project directory, run the following command to create a new custom usecase:

Terminal window
einar generate usecase create-customer

Here’s an example of how the generated code will look:

Terminal window
type CreateCustomer func(ctx context.Context, domain interface{}) (interface{}, error)
func init() {
ioc.Registry(NewCreateCustomer)
}
func NewCreateCustomer() CreateCustomer {
return func(ctx context.Context, input interface{}) (interface{}, error) {
return input, nil
}
}

The file create_customer.go will be created in the following directory structure:

/app
/usecase
- create_customer.go

🪡 Dependency Injection with Einar IOC

Here is how to integrate the usecase.CreateCustomer type as a constructor argument and register its associated dependency with ioc.Registry:

Terminal window
func init() {
ioc.Registry(postCustomer,
serverwrapper.NewEchoWrapper,
usecase.NewCreateCustomer)
}
func postCustomer(
e serverwrapper.EchoWrapper,
createCustomer usecase.CreateCustomer) {
e.POST("/customer", func(c echo.Context) error {
result, _ := createCustomer(c.Request().Context(), "createCustomer dependency injection works")
return c.JSON(http.StatusOK, result)
})
}

🌐 Check The Controller Response

Execute the following POST Request to retrieve createCustomer result from your controller:

Terminal window
curl -X POST http://localhost:8080/customer

ResponseBody:

createCustomer dependency injection works