sm1*_*101 5 c# asp.net-mvc asp.net-core
我正在创建一个 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);
}
Run Code Online (Sandbox Code Playgroud)
在存储库中,我注入了 db 上下文
public class PushNotificationRepository : IPushNotificationRepository
{
private readonly PushNotificationsContext _context;
public PushNotificationRepository(PushNotificationsContext context)
{
_context = context;
}
}
Run Code Online (Sandbox Code Playgroud)
启动类的配置服务如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<IPushNotificationRepository, PushNotificationRepository>();
services.AddDbContextPool<PushNotificationsContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PushNotificationsConnection")));
}
Run Code Online (Sandbox Code Playgroud)
在控制器类中,我使用存储库:
public class ClientsController : Controller
{
//private readonly PushNotificationsContext _context;
private readonly IPushNotificationRepository _pushNotificationRepository;
public ClientsController(IPushNotificationRepository pushNotificationRepository)
{
_pushNotificationRepository = pushNotificationRepository;
}
}
Run Code Online (Sandbox Code Playgroud)
存储库类位于单独的库项目中,该项目由 Web 应用程序项目引用。我收到的错误是:
System.AggregateException: '某些服务无法构建(验证服务描述符时出错'ServiceType: Services.Messaging.Data.Abstract.IPushNotificationRepository Lifetime: Singleton ImplementationType: Services.Messaging.Data.PushNotificationRepository': 无法使用范围服务来自单例“Services.Messaging.Data.Abstract.IPushNotificationRepository”的“Services.Messaging.Data.PushNotificationsContext”。)”
真的很感激这方面的一些建议
单例不能引用 Scoped 实例。错误信息很清楚。
无法从单例使用范围服务“Services.Messaging.Data.PushNotificationsContext”
PushNotificationsContext 被视为范围服务。您几乎不应该使用单例的作用域服务或瞬态服务。您还应该避免从范围服务中使用瞬态服务。使用范围服务注入您需要的内容是一个好习惯,它会在请求后自动清理。
任何一个
services.AddTransient < IPushNotificationRepository, PushNotificationRepository>();
或者
services.AddScoped< IPushNotificationRepository, PushNotificationRepository>();
会正常工作,但请检查您的设计。也许这不是您要寻找的行为。
| 归档时间: |
|
| 查看次数: |
19278 次 |
| 最近记录: |