0
votes

I am creating a project on Core 2.0 and I have been stuck from last 2 days on dependency injection. Following is my code-

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  
    }
}

But when I run my project I am getting error Unable to resolve service for type 'DALUser.Data.ApplicationDbContext' while attempting to activate 'UserAuth.BAL.AccountBAL'. But when I remove IAccountBAL _iAccountBAL from following code it works. B ut I need this dependency to be passed.

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

}
1
There's a lot missing from your ConfigureServices. You're not registering your ApplicationDbContext (that's your actual error) but you're also missing registrations for UserManager, RoleManager and SignInManager.serpent5
@KirkLarkin You saved my rest times. Thank You. It was missing registration of UserManager, RoleManager and SignInManagerRitesh Gupta

1 Answers

1
votes

In your Startup class you need to register your DbContext like this:

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

Here is the example of registering custom Identity based DbContext.