【发布时间】:2020-06-04 21:58:13
【问题描述】:
我正在创建一个 ASP.NET Core Web 应用程序。我正在通过库项目使用存储库。我在 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);
}
在存储库中我注入数据库上下文
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: '有些服务不能 构造(验证服务描述符时出错 '服务类型: Services.Messaging.Data.Abstract.IPushNotificationRepository 生命周期: 单例实现类型: Services.Messaging.Data.PushNotificationRepository':无法使用 范围服务“Services.Messaging.Data.PushNotificationsContext”来自 单身人士 'Services.Messaging.Data.Abstract.IPushNotificationRepository'.)'
非常感谢您对此提出建议
【问题讨论】:
-
将
services.AddSingleton<IPushNotificationRepository, PushNotificationRepository>();更改为services.AddScoped<IPushNotificationRepository, PushNotificationRepository>();
标签: c# asp.net-mvc asp.net-core