异常DI解决方案新查询,但我不喜欢任何新的解决方案和帮助ı总是重试问题解决方案


namespace Sozluk.Api.Application.Extensions;
public static class Registration
{
public static IServiceCollection AddApplicationRegistration(this IServiceCollection services)
{
var assm = Assembly.GetExecutingAssembly();
services.AddMediatR(assm);
services.AddAutoMapper(assm);
services.AddValidatorsFromAssembly(assm);
return services;
}
}

在此处输入图像描述

namespace Sozluk.Infrastructure.Persistence.Extensions;
public static class Registration
{
public static IServiceCollection AddInfrastructureRegistration(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<SozlukContext>(conf =>
{
var connStr = configuration["SozlukDbConnectionStrings"].ToString();
conf.UseSqlServer(connStr, opt =>
{
opt.EnableRetryOnFailure();
});
});
services.AddScoped<IUserRepository, UserRepository>();
return services;
}
}

我认为问题在于IUserRepository的作用域没有在LoginUserCommandHandler内部创建。

请注入您的LoginUserCommandHandlerIServiceScopeFactory而不是IUserRepository:

private IServiceScopeFactory _serviceScopeFactory;
public LoginUserCommandHandler(IServiceScopeFactory serviceScopeFactory) 
{
_serviceScopeFactory = serviceScopeFactory;
}

接下来,一旦您需要使用IUserRepository的实例,请为其创建一个范围,然后使用下一个代码:

using (var scope = _serviceScopeFactory.CreateScope())
{
IUserRepository instanceUserRepository = scope.ServiceProvider.GetRequiredService<IUserRepository>();
}

相关内容

  • 没有找到相关文章

最新更新