Defects on surfaces of semiconductors have a strong effect on their reactivity and catalytic properties. The concentration of different charge states of defects is determined by their formation energies. First-principles calculations are an important tool for computing defect formation energies and for studying the microscopic environment of the defect. The main problem associated with the widely used supercell method in these calculations is the error in the electrostatic energy, which is especially pronounced in calculations that involve surface slabs and two-dimensional materials. We present an internally consistent approach for calculating defect formation energies in inhomogeneous and anisotropic dielectric environments and demonstrate its applicability to the cases of the positively charged Cl vacancy on the NaCl (100) surface and the negatively charged S vacancy in monolayer MoS2.