title: How to retrieve a service in razor pages with dependency injection
body: <p>In ASP.NET Core 2 application I set up some services:</p>
  
  <pre><code> public void ConfigureServices(IServiceCollection services)
   {
      services.AddDbContext&lt;MyContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString("MyContext")));
      services.AddHangfire(options =&gt; options.UseSqlServerStorage(Configuration.GetConnectionString("MyContext")));
      services.AddOptions();
      services.Configure&lt;MySettings&gt;(options =&gt; Configuration.GetSection("MySettings").Bind(options));
      services.AddMvc().AddDataAnnotationsLocalization();
  
      services.AddScoped&lt;IMyContext, MyContext&gt;();
      services.AddTransient&lt;IFileSystem, FileWrapper&gt;();
      services.AddTransient&lt;Importer, Importer&gt;();
   }
  </code></pre>
  
  <p>In <code>program.cs</code> I'm able to retrieve my own Service:</p>
  
  <pre><code>var host = BuildWebHost(args);
  using (var scope = host.Services.CreateScope())
  {
      var services = scope.ServiceProvider;
      var ip = services.GetRequiredService&lt;Importer&gt;();
      Task task = ip.ImportListAsync();
  }
  </code></pre>
  
  <p>Now I'm trying to understand how to do the same when I don't have the host variable, like in any other C# class or even if a cshtml page:</p>
  
  <pre><code>public async Task&lt;IActionResult&gt; OnPostRefresh()
  {
      if (!ModelState.IsValid)
      {
          return Page();
      }
  
      // host is not defined: how to retrieve it?
      using (var scope = host.Services.CreateScope())
      {
          var services = scope.ServiceProvider;
          var ip = services.GetRequiredService&lt;Importer&gt;();
          Task task = ip.ImportListAsync();
      }
  
      return RedirectToPage();
  }
  </code></pre>