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:
einar generate usecase create-customerHere’s an example of how the generated code will look:
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:
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:
curl -X POST http://localhost:8080/customerInvoke-WebRequest -Uri http://localhost:8080/customer -Method POSTResponseBody:
createCustomer dependency injection works