【问题标题】:Unable to resolve service for type '' while attempting to activate ''尝试激活“”时无法解析类型“”的服务
【发布时间】:2018-09-17 14:37:04
【问题描述】:

我正在 Core 2.0 上创建一个项目,但从过去 2 天开始,我一直在依赖注入。以下是我的代码-

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddTransient<IAccountBAL, AccountBAL>();
}

public interface IAccountBAL
{
    Task CreateSuperAdmin();
}

public class AccountBAL:IAccountBAL
{
    private ApplicationDbContext _connection;
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly UserManager<ApplicationUser> _userManager;
    public AccountBAL(ApplicationDbContext connection, RoleManager<IdentityRole> roleManager, SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager)
    {
        _connection = connection;
        _roleManager = roleManager;
        _signInManager = signInManager;
        _userManager = userManager; 
    }
    public async Task CreateSuperAdmin()
    {
        //My Code  
    }
}

但是当我运行我的项目时,我收到错误在尝试激活“UserAuth.BAL.AccountBAL”时无法解析类型“DALUser.Data.ApplicationDbContext”的服务。 但是,当我从以下代码中删除 IAccountBAL _iAccountBAL 时,它可以工作。但是我需要传递这种依赖关系。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAccountBAL _iAccountBAL)
{

}

【问题讨论】:

  • 您的ConfigureServices 缺少很多内容。您没有注册ApplicationDbContext(这是您的实际错误),但您也缺少UserManagerRoleManagerSignInManager 的注册。
  • @KirkLarkin 你节省了我的休息时间。谢谢你。缺少 UserManager、RoleManager 和 SignInManager 的注册

标签: c# asp.net-core asp.net-core-2.0


【解决方案1】:

在您的Startup 课程中,您需要像这样注册您的DbContext

public void ConfigureServices(IServiceCollection services)
{
    // ... 
    services.AddDbContext<ApplicationDbContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    });
    // ...
}

这里是example of registering custom Identity based DbContext

【讨论】:

  • 在我的情况下,它缺少 UserManager、RoleManager 和 SignInManager 的注册。休息一下,你的答案是可以接受的。
  • 如果您按照我提供的链接来配置您自己的基于IdentityDBContext - 您将拥有所有需要的注册权限。
猜你喜欢
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 2019-02-04
相关资源
最近更新 更多