gmaps-api-net icon indicating copy to clipboard operation
gmaps-api-net copied to clipboard

Make gmaps DI (depedency injection) friendly library

Open ericnewton76 opened this issue 7 years ago • 5 comments

I believe this requires some refactoring that might slightly modify the public interfaces, but for a good cause: depedency injection and inversion of control concepts.

For instance, instead of

var request = new GeocodingRequest();
request.Address = "1600 Amphitheatre Parkway";
request.Sensor = false;
var response = new GeocodingService().GetResponse(request);

DI friendly public interfaces would make the following code, which is much more DI friendly itself:

public class Consumer 
{
  private IGeocodingService _GeocodingService;
  public Consumer(IGeocodingService GeocodingService) { ... }
   
  public void DoWork()
  {
    IGeocodingRequest request = _GeocodingService.CreateRequest();
    request.Address = "1600 Amphitheatre Parkway";
    var response = _GeocodingService.GetResponse(request);
  }
}

ericnewton76 avatar Jul 20 '17 20:07 ericnewton76

I think it's a great idea to define an interface for each service so that it can be easily mocked for consumers while testing. Something simple like:

public interface IGeocodingService
{
  GeocodingResponse GetResponse(GeocodingRequest request);
}

I struggle to imagine a scenario where somebody would want to swap out Gmaps with something else but still use our interfaces though, and isn't that what you'd use DI for?

richardthombs avatar Jul 20 '17 21:07 richardthombs

Not exactly, it's more for the consumers of this library to be able to mock the gmaps away from their unit/integration testing

And your sample would look like this instead:

public interface IGeocodingService
{
  IGeocodingRequest CreateRequest();
  IGeocodingResponse GetResponse(IGeocodingRequest request);
}

ericnewton76 avatar Jul 20 '17 23:07 ericnewton76

Why would the request and response objects need interfaces?

richardthombs avatar Jul 21 '17 04:07 richardthombs

for the same mocking reasons. in DI preferably everything is an interface, makes it much easier to mock

And realistically the request and response objects already have an interface... the implicit one... =D

ericnewton76 avatar Jul 21 '17 19:07 ericnewton76

btw, here's what I'm considering: https://stackoverflow.com/a/2047657/323456

but then theres: http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/

Ugh, after reading all this, it would be safest to go with the simpler HttpWebRequest.BeginGetRequest but within a Task worker to async out the initial steps that BeginGetRequest still performs on the current thread: dns lookups, socket acquiring, etc. https://stackoverflow.com/questions/202481/how-to-use-httpwebrequest-net-asynchronously and be mindful of the third answer: https://stackoverflow.com/a/13963255/323456 which is to wrap BeginGetRequest in a Action worker delegate

ericnewton76 avatar Jul 21 '17 19:07 ericnewton76