Dependency Injection and the Url object I'm making the leap from Drupal 7 to Drupal 8 and am still fuzzy on some core concepts, particularly relating to dependency injection (DI). I've read plenty of tutorials and have a grasp on DI with services, but am unclear on using DI with something like \Drupal::Url().

For instance, I am using the following code in a class:

use Drupal\Core\Url;
...
$url = Url::fromRoute('&lt;current&gt;', [], ['absolute' =&gt; 'true'])-&gt;toString();


From what I can tell, there is no Url service. So, what I am wondering is: Is it possible to access Url via DI? And if so, how?

Bonus points: I intend for the class I am writing to be used as a service. Does this have any impact on the answer?

Edit: Fixed erroneous code.

Edit 2: I should also point out that the purpose of this call is to retrieve the current absolute URL so that I can determine if it is HTTPS.
You can inject the UrlGenerator as service and use UrlGenerator::generateFromRoute, but in the linked doc you are discouraged to do so:


  @internal Should not be used in user code. Use \Drupal\Core\Url
  instead.


So the code in your question to create an url object is OK for a service, but not the toString() method. Render the url only with this method when the page rendering process has started, for example in a theme. 

In a service you usually don't know this and you should return an unrendered url object, so that it can be rendered later in the rendering pipeline.

$url = Url::fromRoute('&lt;current&gt;', [], ['absolute' =&gt; 'true']);


toString() in the wrong place generates ugly error messages about early rendering which are hard to debug when this happens somewhere in a service.