This can't be in a migration. The code has an assertion that this is only called once, so if a future migration were to do the same thing the running of the migrations would barf.

It's likely the DB migrations stuff needs to do some state set up before it runs, this potentially being a candidate. Though I'm not 100% why this one is needed (the factory initialization below definitely is). I may be wrong, but this is only needed when actually assigning or using a plugin, neither of which is needed to do the DB copies that are used by this script. It's possible the association manager is checking it for some reason. Do you remember the error you were seeing without this?