From Alan Mikhail, author of The Animal in Ottoman Egypt:
It’s no surprise that the first Muslims had so many dogs. Most of them kept large flocks of sheep and goats, and dogs helped to manage and protect these other animals, preventing them from running away and scaring off would-be thieves and predators. Sheep and goats were these early Muslims’ food and capital, and dogs helped to protect these investments.
[…]
As Islam spread throughout the Middle East and the world, it moved from being a religion of nomadic peoples to one centered in cities. Many of the world’s largest cities in the millennium between 700 and 1700 were Muslim cities. As they did in the countryside, in cities too dogs played vital roles. They of course continued to protect property and shoo away intruders, but in cities dogs served an even more important function—they ate garbage. From Damascus and Baghdad to Cairo and Istanbul, urban authorities supported dog populations as consumers of waste to keep city streets clean. Muslim leaders built watering troughs for dogs, many mosques threw out food for them, and butchers used them to keep away rats and other vermin. Humans who committed violence against urban canines were often punished. Muslim cities were much cleaner and more pleasant places with dogs than without them.
All of this meant that Muslims throughout the world were in regular daily contact with the many dogs in their midst. They recognized how useful canines were as guards and cleaning agents and, we can only presume, developed quite intimate relationships with them built around regular contact and the kind of affection bred from codependence.