you need to set their engagement range to be local area only. If your building new units at the same time you need to create a fleet with the units stationed there. Set the engagement range of the fleet to local area only. Then set the rally point of the factories to the fleet leader icon.
Newly built units will then join that fleet and will be automatically set to local area only engagement.
This is one of the few times I use the fleet option online so I don't have to baby sit units suiciding themselves after being built.