title: Cannot resolve scoped service from root provider .Net Core 2
body: <p>When I try to run my app I get the error </p>
  
  <pre><code>InvalidOperationException: Cannot resolve 'API.Domain.Data.Repositories.IEmailRepository' from root provider because it requires scoped service 'API.Domain.Data.EmailRouterContext'.
  </code></pre>
  
  <p>What's odd is that this EmailRepository and interface is set up exactly the same as far as I can tell as all of my other repositories yet no error is thrown for them.  The error only occurs if I try to use the app.UseEmailingExceptionHandling(); line. Here's some of my Startup.cs file.</p>
  
  <pre><code>public class Startup
  {
      public IConfiguration Configuration { get; protected set; }
      private APIEnvironment _environment { get; set; }
  
      public Startup(IConfiguration configuration, IHostingEnvironment env)
      {
          Configuration = configuration;
  
          _environment = APIEnvironment.Development;
          if (env.IsProduction()) _environment = APIEnvironment.Production;
          if (env.IsStaging()) _environment = APIEnvironment.Staging;
      }
  
      public void ConfigureServices(IServiceCollection services)
      {
          var dataConnect = new DataConnect(_environment);
  
          services.AddDbContext&lt;GeneralInfoContext&gt;(opt =&gt; opt.UseSqlServer(dataConnect.GetConnectString(Database.GeneralInfo)));
          services.AddDbContext&lt;EmailRouterContext&gt;(opt =&gt; opt.UseSqlServer(dataConnect.GetConnectString(Database.EmailRouter)));
  
          services.AddWebEncoders();
          services.AddMvc();
  
          services.AddScoped&lt;IGenInfoNoteRepository, GenInfoNoteRepository&gt;();
          services.AddScoped&lt;IEventLogRepository, EventLogRepository&gt;();
          services.AddScoped&lt;IStateRepository, StateRepository&gt;();
          services.AddScoped&lt;IEmailRepository, EmailRepository&gt;();
      }
  
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      {
          loggerFactory.AddConsole();
  
          app.UseAuthentication();
  
          app.UseStatusCodePages();
          app.UseEmailingExceptionHandling();
  
          app.UseMvcWithDefaultRoute();
      }
  }
  </code></pre>
  
  <p>Here is the EmailRepository</p>
  
  <pre><code>public interface IEmailRepository
  {
      void SendEmail(Email email);
  }
  
  public class EmailRepository : IEmailRepository, IDisposable
  {
      private bool disposed;
      private readonly EmailRouterContext edc;
  
      public EmailRepository(EmailRouterContext emailRouterContext)
      {
          edc = emailRouterContext;
      }
  
      public void SendEmail(Email email)
      {
          edc.EmailMessages.Add(new EmailMessages
          {
              DateAdded = DateTime.Now,
              FromAddress = email.FromAddress,
              MailFormat = email.Format,
              MessageBody = email.Body,
              SubjectLine = email.Subject,
              ToAddress = email.ToAddress
          });
          edc.SaveChanges();
      }
  
      public void Dispose()
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }
  
      private void Dispose(bool disposing)
      {
          if (!disposed)
          {
              if (disposing)
                  edc.Dispose();
              disposed = true;
          }
      }
  }
  </code></pre>
  
  <p>And finally the exception handling middleware</p>
  
  <pre><code>public class ExceptionHandlingMiddleware
  {
      private const string ErrorEmailAddress = "errors@ourdomain.com";
      private readonly IEmailRepository _emailRepository;
  
      private readonly RequestDelegate _next;
  
      public ExceptionHandlingMiddleware(RequestDelegate next, IEmailRepository emailRepository)
      {
          _next = next;
          _emailRepository = emailRepository;
      }
  
      public async Task Invoke(HttpContext context)
      {
          try
          {
              await _next.Invoke(context);
          }
          catch (Exception ex)
          {
              await HandleExceptionAsync(context, ex, _emailRepository);
          }
      }
  
      private static Task HandleExceptionAsync(HttpContext context, Exception exception,
          IEmailRepository emailRepository)
      {
          var code = HttpStatusCode.InternalServerError; // 500 if unexpected
  
          var email = new Email
          {
              Body = exception.Message,
              FromAddress = ErrorEmailAddress,
              Subject = "API Error",
              ToAddress = ErrorEmailAddress
          };
  
          emailRepository.SendEmail(email);
  
          context.Response.ContentType = "application/json";
          context.Response.StatusCode = (int) code;
          return context.Response.WriteAsync("An error occured.");
      }
  }
  
  public static class AppErrorHandlingExtensions
  {
      public static IApplicationBuilder UseEmailingExceptionHandling(this IApplicationBuilder app)
      {
          if (app == null)
              throw new ArgumentNullException(nameof(app));
          return app.UseMiddleware&lt;ExceptionHandlingMiddleware&gt;();
      }
  }
  </code></pre>
  
  <p>Update:
  I found this link <a href="https://github.com/aspnet/DependencyInjection/issues/578" rel="noreferrer">https://github.com/aspnet/DependencyInjection/issues/578</a> which led me to change my Program.cs file's BuildWebHost method from this</p>
  
  <pre><code>public static IWebHost BuildWebHost(string[] args)
  {
      return WebHost.CreateDefaultBuilder(args)
          .UseStartup&lt;Startup&gt;()
          .Build();
  }
  </code></pre>
  
  <p>to this</p>
  
  <pre><code>public static IWebHost BuildWebHost(string[] args)
  {
      return WebHost.CreateDefaultBuilder(args)
          .UseStartup&lt;Startup&gt;()
          .UseDefaultServiceProvider(options =&gt;
              options.ValidateScopes = false)
          .Build();
  }
  </code></pre>
  
  <p>I don't know what exactly is going on but it seems to work now.</p>