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
内部创建。
请注入您的LoginUserCommandHandler
IServiceScopeFactory
而不是IUserRepository
:
private IServiceScopeFactory _serviceScopeFactory;
public LoginUserCommandHandler(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
接下来,一旦您需要使用IUserRepository
的实例,请为其创建一个范围,然后使用下一个代码:
using (var scope = _serviceScopeFactory.CreateScope())
{
IUserRepository instanceUserRepository = scope.ServiceProvider.GetRequiredService<IUserRepository>();
}