![](/img/trans.png)
[英]System.InvalidOperationException: Unable to resolve service for type 'ChatBotDashboard.ApplicationDbContext' while attempting to activate Controller
[英]Unable to resolve service for type in ApplicationDbContext
當我嘗試使用dnx ef migrations add Mig
,我在控制台中有以下異常:
嘗試激活“NewLibrary.Models.ApplicationDbContext”時,無法解析類型“Microsoft.AspNet.Http.IHttpContextAcccessor”的服務。
我的ApplicationDbContext :
public class ApplicationDbContext : DbContext
{
private readonly IHttpContextAccessor _accessor;
public ApplicationDbContext(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
}
有什么問題?
我應該如何正確地向ApplicationDbContext
構造函數添加依賴項?
DI不會通過命令行設置,這就是你得到上述異常的原因。
在評論中,您解釋了您希望通過IHttpContextAccessor
訪問HttpContext
,這通常在運行時可用。
遷移不會在運行時應用,其中DI已經配置並且可用。
您可能需要閱讀配置DbContext 。 本文檔適用於EF7以上版本
我發現這個論壇讓我得到了以下解決方案: https : //github.com/aspnet/EntityFrameworkCore/issues/4232
創建一個新的服務類和接口:
using Microsoft.AspNetCore.Http;
using MyProject.Interfaces;
using System.Collections.Generic;
using System.Linq;
namespace MyProject.Web.Services
{
public interface IUserResolverService
{
string GetCurrentUser();
}
public class UserResolverService : IUserResolverService
{
private readonly IHttpContextAccessor _context;
public UserResolverService(IEnumerable<IHttpContextAccessor> context)
{
_context = context.FirstOrDefault();
}
public string GetCurrentUser()
{
return _context?.HttpContext?.User?.Identity?.Name ?? "unknown_user";
}
}
}
並將其注冊到您的DI容器(例如Startup.cs)
services.AddTransient<IUserResolverService, UserResolverService>();
然后在您的DbContext中,使用userResolverService獲取用戶名而不是IHTTPContextAccessor
private readonly IUserResolverService userResolverService;
public ApplicationDbContext(IUserResolverService userResolverService) : base()
{
this.userResolverService = userResolverService;
var username = userResolverService.GetCurrentUser();
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.