Error: could not lookup MyApp.Repo because it was not started or it does not exist

Hello,

I want to start a module (MyApp.MyAgent) using Agent that will fetch some data from DB (and thus use MyApp.Repo) and keep it in memory, and I want the data to be available when the application starts. So I add it as a child to the superviser but the compiler complains that MyApp.Repo has not yet been started when aliasing it in MyApp.MyAgent:

def start(_type, _args) do
  # List all child processes to be supervised
  children = [
    # Start the Ecto repository
    MyApp.Repo,
    # Start the endpoint when the application starts
    MyAppWeb.Endpoint,
    # Starts a worker by calling: MyApp.Worker.start_link(arg)
    # {MyApp.Worker, arg},
    MyApp.MyAgent.start_link()
  ]
defmodule MyApp.MyAgent do
  import Ecto.Query, warn: false
  alias MyApp.Repo
  alias MyApp.SomeContext.SomeSchema

  def start_link do
    ids = Repo.all(from s in SomeSchema, select: s.id)

    Agent.start_link(fn -> ids end, name: __MODULE__)
  end

  def all do
    Agent.get(__MODULE__, & &1)
  end
end

Thank you for any help!

Do not call start link, but provide a childspec as in the already existing items.

2 Likes

Calling start_link is effectively a “start this now” and it returns the pid of the started process, while childspecs are just data, which tells the supervisor how to start children, when it’s in the place to start a certain child at a later time, e.g. when the supervisor itself starts or when a child is restarted.

2 Likes