![](/img/trans.png)
[英]“Cannot resolve scoped service from root provider” with custom EF Core SeriLog Sink
[英]Cannot resolve scoped service from root provider .Net Core 2
当我尝试运行我的应用程序时出现错误
InvalidOperationException: Cannot resolve 'API.Domain.Data.Repositories.IEmailRepository' from root provider because it requires scoped service 'API.Domain.Data.EmailRouterContext'.
奇怪的是,就我所知,这个 EmailRepository 和界面的设置与我所有其他存储库完全相同,但没有为它们抛出任何错误。 该错误仅在我尝试使用 app.UseEmailingExceptionHandling(); 时发生; 线。 这是我的一些 Startup.cs 文件。
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<GeneralInfoContext>(opt => opt.UseSqlServer(dataConnect.GetConnectString(Database.GeneralInfo)));
services.AddDbContext<EmailRouterContext>(opt => opt.UseSqlServer(dataConnect.GetConnectString(Database.EmailRouter)));
services.AddWebEncoders();
services.AddMvc();
services.AddScoped<IGenInfoNoteRepository, GenInfoNoteRepository>();
services.AddScoped<IEventLogRepository, EventLogRepository>();
services.AddScoped<IStateRepository, StateRepository>();
services.AddScoped<IEmailRepository, EmailRepository>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseAuthentication();
app.UseStatusCodePages();
app.UseEmailingExceptionHandling();
app.UseMvcWithDefaultRoute();
}
}
这是电子邮件存储库
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;
}
}
}
最后是异常处理中间件
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<ExceptionHandlingMiddleware>();
}
}
更新:我发现这个链接https://github.com/aspnet/DependencyInjection/issues/578这导致我改变了我的 Program.cs 文件的 BuildWebHost 方法从此
public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
对此
public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseDefaultServiceProvider(options =>
options.ValidateScopes = false)
.Build();
}
我不知道到底发生了什么,但现在似乎可以工作了。
您在Startup
类中将IEmailRepository
注册为范围服务。 这意味着您不能将其作为构造函数参数注入Middleware
因为只有Singleton
服务可以通过Middleware
的构造函数注入来解析。 您应该将依赖项移动到Invoke
方法,如下所示:
public ExceptionHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IEmailRepository emailRepository)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex, emailRepository);
}
}
另一种获取作用域依赖实例的方法是将服务提供者( IServiceProvider
)注入到中间件构造函数中,在Invoke
方法中创建scope
,然后从作用域中获取所需的服务:
using (var scope = _serviceProvider.CreateScope()) {
var _emailRepository = scope.ServiceProvider.GetRequiredService<IEmailRepository>();
//do your stuff....
}
查看在asp.net 核心依赖项注入最佳实践提示技巧中的方法体中解析服务以获取更多详细信息。
中间件始终是单例,因此您不能将作用域依赖项作为中间件构造函数中的构造函数依赖项。
中间件支持 Invoke 方法的方法注入,因此您只需将 IEmailRepository emailRepository 作为参数添加到该方法,它将被注入到那里,并且在作用域范围内都可以。
public async Task Invoke(HttpContext context, IEmailRepository emailRepository)
{
....
}
您的middleware
和service
必须相互兼容,以便通过middleware
的constructor
注入service
。 在这里,您的middleware
已创建为基于convention-based middleware
,这意味着它充当singleton service
并且您已将服务创建为scoped-service
。 因此,您不能将scoped-service
注入到singleton-service
scoped-service
的构造函数中,因为它强制scoped-service
充当singleton
scoped-service
。 但是,这里有您的选择。
InvokeAsync
方法。middleware
转换factory-based
middleware
。 Factory-based middleware
能够充当scoped-service
。 因此,您可以通过该中间件的构造函数注入另一个scoped-service
。 下面,我向您展示了如何创建基于factory-based
中间件。
这仅用于演示。 所以,我已经删除了所有其他代码。
public class Startup
{
public Startup()
{
}
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<TestMiddleware>();
services.AddScoped<TestService>();
}
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<TestMiddleware>();
}
}
测试TestMiddleware
:
public class TestMiddleware : IMiddleware
{
public TestMiddleware(TestService testService)
{
}
public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
return next.Invoke(context);
}
}
TestService
:
public class TestService
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.