The way I've figured it happens is (Personal gnosis alert! I can cite nothing!) there could have been something within you that was compatible with whatever possessed you. It could be a waning spiritual immunity, or it could be something like a hole in your aura into which it could fit, or a whole lot of emptiness on some level where the possessor could easily fit, or it could be a characteristic that you and the possesser share--back to spiritual immunity, your "immune system" isn't going to fight off something that it recognizes as a part of you.
So, the way that I would (and have) stopped that happening again is recognize that our conscious self is just the tip of a quantum flux iceberg. We've got to test the waters, and realize what the waves are bringing, so as to better manage it. You could fill the emptiness where it waits, or where something else has the potential to come in. You could see how to change the parts that are too alike something else. You can also (I mean... I did...) recognize how the self is so dependent on context and conditions that what used to be like possession is just another deeply-seated facet of personality.
Or... haematite, tiger's eye, sage smudge or bell-ringing cleansing... stuff.
Sorry if most of this wasn't helpful. I usually give theory more than how-to's, here that usually means giving the orange answer to a blue question.