Iris: [BUG] When using Dependency Injection , Iris call new method everytime to create a new struct

Created on 21 Jul 2020  ·  5Comments  ·  Source: kataras/iris

Describe the bug
When passing in New function into

app.Register(
    environment.New
    // ...dependencies
)

When requesting endpoints , the New function will run again. Shouldn't the result of the new constructor be stored in some kind of bean factory instead ?

To Reproduce
Steps to reproduce the behavior:

  1. Create a Iris project.
  2. Setup mvc.
  3. in the Dependencies new function fmt.Println some sentences
  4. register dependencies in the mvc
  5. register the controller and use the dependencies in that controller
  6. start the application and request the endpoint
  7. should see println in New function print out everytime when requesting endpoint.

Expected behavior
New function should be called once only , but not everytime when there is request.

Screenshots
Screenshot 2020-07-21 at 11 00 49 AM

the Json is the configuration I printed from environment struct new function.
the line beneath it is the log in controller method

Desktop (please complete the following information):

  • OS: MAC
resolved bug

All 5 comments

@sheunglaili In Iris we have two bindings mode, static and request-scope (dynamic) and there is a smart factory, that's why Iris' MVC is the fastest out there . If I don't see your // ...dependencies I can't tell you what type your dependency is. Please post a code snippet that I can run, this is missing the important part.

so for static , does that means we have to wire up our bean first ?

        logger := app.Logger()
        profileAPI := app.Party("/api")

    mvc.Configure(profileAPI, func(app *mvc.Application) {

        env := environment.New(logger)

        db := database.New(env, logger)

        app.Register(
            logger,
            env,
            db,
            service.NewProfileService,
        )

        app.Handle(new(controller.ProfileController))
    })

like that ?

so what if there is a lot dependencies ? so what to wire it up ourselves before register them ?

@kataras I have written some demo code in https://github.com/sheunglaili/iris-DI-issue

you can see when you request it the GET localhost:8080/api/ , the log in server will indicate the dependency is reinitialized again.

That was an issue because a dependency depend on other dependencies and you are right, if all accepted dependencies are static so the user of those should be static too. Fixed on master branch. Thanks a lot @sheunglaili!

thanks a lot @kataras

Was this page helpful?
0 / 5 - 0 ratings