我正在创建一个ASP.NET Core Web应用程序。我通过一个库项目使用Repository。我在Web应用程序项目中引用它。
存储库接口如下:
public interface IPushNotificationRepository
{
IQueryable<PushNotification> Notifications
{
get;
}
IQueryable<Client> Clients
{
get;
}
void Add(PushNotification notification);
void Add(Client client);
void AddRange(IList<PushNotification> notifications);
bool AddIfNotAlreadySent(PushNotification notification);
void UpdateDelivery(PushNotification notification);
bool CheckIfClientExists(string client);
Client FindClient(int? id);
void Update(Client client);
void Delete(Client client);
}
在仓库中,我注入了db上下文。
public class PushNotificationRepository : IPushNotificationRepository
{
private readonly PushNotificationsContext _context;
public PushNotificationRepository(PushNotificationsContext context)
{
_context = context;
}
}
启动类的配置服务如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<IPushNotificationRepository, PushNotificationRepository>();
services.AddDbContextPool<PushNotificationsContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PushNotificationsConnection")));
}
在控制器类中,我使用存储库:
public class ClientsController : Controller
{
//private readonly PushNotificationsContext _context;
private readonly IPushNotificationRepository _pushNotificationRepository;
public ClientsController(IPushNotificationRepository pushNotificationRepository)
{
_pushNotificationRepository = pushNotificationRepository;
}
}
存储库类在一个单独的库项目中,该项目被 Web 应用程序项目引用。我收到的错误信息是:
System.AggregateException: “某些服务无法构建(Error while validating the service descriptor 'ServiceType: Services.Messaging.Data.Abstract.IPushNotificationRepository Lifetime: Singleton ImplementationType: Services.Messaging.Data.PushNotificationRepository': Cannot consume scoped service 'Services.Messaging.Data.PushNotificationsContext' from singleton 'Services.Messaging.Data.Abstract.IPushNotificationRepository'.)”。
真的很希望能得到一些关于此问题的建议。
services.AddSingleton<IPushNotificationRepository, PushNotificationRepository>();
更改为services.AddScoped<IPushNotificationRepository, PushNotificationRepository>();
。 - Vidmantas Blazevicius