C# Dependency Injection – Communicating Between Unaware Objects

cdependency-injectioninversion-of-control

I am trying to improve my programming skills and knowledge and I have been doing some reading about various design patterns and youtubing videos etc.
One subject I thought was interesting was about Singletons being an Anti-pattern which has lead me on to a problem that I am not quite sure how to solve. Allow me to explain.
Lets say I have created a GPS class library. In the library I have a class called GpsSensorUtil. This class does everything to do with processing GPS data such as working out speed, distance etc and fires events with this information.
So now I'm thinking hey, maybe I want to see the GPS info visually. So I create a UserControl in the library which will listen to the events of the GpsSensorUtil.

The issue I am thinking about is how can I wire up the GpsSensorUtil to the UserControl so that the UserControl can listen to Events from the GpsSensorUtil?
In a normal application I would be looking into DependancyInjection maybe with Unity, but then I would need to find a way of initialising and configuring the UnityContainer as there is no entry point in a class library.
I did think of creating like a singleton to be a static reference for the container but as I have been reading, this is not a good thing.

In my head the following needs considering.

  1. GpsSensorUtil does not know of the UserControl and does not need too.
  2. UserControler does not need to know of the GpsSensorUtil, only the events it fires.
  3. Anyone could use this library so I don't want to constrain to one IoC like unity.

What's the best way to approach something like this?

Best Answer

If you're making a UI for the GPS data, it will invariably have a dependency on GPS data of some sort. Having that coupling isn't bad - quite the opposite. By having your user control depend on an explicit interface, you're letting the compiler be able to tell you when it's missing and you're telling your users what it needs to work.

By making it an interface though, you're effectively decoupling your control from the implementation of the GPS data provider allow it to change freely. How the dependency gets supplied is up to the user, who could even use their own data source if they wanted to. No need for accursed IoC containers if they're not warranted.