Hacker News new | ask | show | jobs
by dangoor 1569 days ago
We at Khan Academy are planning a blog post soon about how we've been approaching dependency injection in Go. I touched upon this in my GopherCon talk last year[1]. I like the system because it's pretty straightforward and builds upon Go's context with a bit of reflection:

[1]: https://youtu.be/MysHL0XYJeA?t=680

    var ktx interface {
        kacontext.Base
        log.KAContext
        datastore.KAContext
        gqlclient.KAContext
        web.AuthedServiceContext
        web.AuthedUserContext
    } = kacontext.Upgrade(ctx)
With this approach, you ask for the just the interfaces you need from the context and you have statically typed access to those resources.

I expect the blog post will be live within a couple of weeks (but haven't seen a draft yet, so no guarantees): https://blog.khanacademy.org/engineering

1 comments

Not a fan of that... Feels like an abuse of Context. I admit, I thought about this a long time ago, Context is passed all the way down the stack, it's just so easy to abuse. But it's just one of those things that completely hides this away from anyone who glances at your code.

It makes it incredibly easy to create "God structs" that can do everything. They have access to every service in your application when really you should be limiting the scope of them.

Unsatisfied dependencies are now a runtime issue, not a buildtime issue, one of my biggest gripes when working with IOC containers in .NET.

Not to mention that Context, originally built as a cancellation token, is now doubling as a service locator? It feels like something completely adjacent to what a Context is.

This is the exact sort of reflection magic code that a lot of Go developers dislike. And there's nothing that this gives you that passing dependencies as parameters can't. If you've got too many to pass then you're doing too much and you're not separating concerns.

Passing context everywhere is quite ironic in a language that is supposedly "non-colored" when it comes to being able to call any function concurrently. In practice however, passing context becomes that function's color.

Project Loom in Java will solve this problem in a much more superior manner.