尝试激活“”时无法解析“”类型的服务

时间:2018-09-17 14:37:04

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

我正在Core 2.0上创建一个项目,最近两天因依赖项注入而陷入困境。以下是我的代码-

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)
{

}

1 个答案:

答案 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