The problem of inhibiting viral DNA ejection from bacteriophages by multivalent counterions, specifically Mg$^{+2}$ counterions, is studied. Experimentally, it is known that MgSO$_4$ salt has a strong and non-monotonic effect on the amount of DNA ejected. There exists an optimal concentration at which the minimum amount of DNA is ejected from the virus. At lower or higher concentrations, more DNA is ejected from the capsid. We propose that this phenomenon is the result of DNA overcharging by Mg$^{+2}$ multivalent counterions. As Mg$^{+2}$ concentration increases from zero, the net charge of DNA changes from negative to positive. The optimal inhibition corresponds to the Mg$^{+2}$ concentration where DNA is neutral. At lower/higher concentrations, DNA genome is charged. It prefers to be in solution to lower its electrostatic self-energy, which consequently leads to an increase in DNA ejection. By fitting our theory to available experimental data, the strength of DNA$-$DNA short range attraction energies, mediated by Mg$^{+2}$, is found to be $-$0.004 $k_BT$ per nucleotide base. This and other fitted parameters agree well with known values from other experiments and computer simulations. The parameters are also in aggreement qualitatively with values for tri- and tetra-valent counterions.