Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
Excuse me for maybe asking this, but i am just a beginner in using ASP.NET MVC/C#. I am in a group project with 3 other classmates, but we can't seem to figure out how to solve this issue.
I am trying to run this project but it gives me the following error:
"InvalidOperationException: Unable to resolve service for type >'BusinessLogic.LoginManager' while attempting to activate >'B3.Controllers.HomeController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServ>iceProvider sp, Type type, Type requiredBy, bool >isDefaultParameterRequired)"
We got two database connections with two seperate dbContext classes. So what i can tell from the error (if i am not mistaken that is) it has some troubles with dependency injection?
I am sorry in advance if the code is a bit messy. If you want to see some other classes as well then I am willing to share them.
HomeController
public class HomeController : Controller
private LoginManager loginManager;
public HomeController(LoginManager login)
loginManager = login;
public IActionResult Login()
return View();
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel loginModel)
if (ModelState.IsValid)
if (await loginManager.LoginUser(loginModel))
return Redirect("/Overview/Index");
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(loginModel);
return View("Login", loginModel);
public async Task<IActionResult> Logout()
await loginManager.LogOut();
return Redirect("/");
public IActionResult SignUp()
return View("AddUser");
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SignUp(LoginModel loginModel)
if (ModelState.IsValid)
string message = await loginManager.SignUp(loginModel);
if (message.Equals("Success"))
return Redirect("/");
ModelState.AddModelError(string.Empty, message);
return View("AddUser");
return View();
LoginManager
public class LoginManager
private UserManager<IdentityUser> _userManager;
private SignInManager<IdentityUser> _signInManager;
private IEmployeeRepository _employeeRepository;
public LoginManager(IEmployeeRepository employeeRepo, UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
_employeeRepository = employeeRepo;
_userManager = userManager;
_signInManager = signInManager;
public async Task<bool> LoginUser(LoginModel loginModel)
IdentityUser applicationUser = await _userManager.FindByNameAsync(loginModel.Name);
if (applicationUser != null)
await _signInManager.SignOutAsync();
if ((await _signInManager.PasswordSignInAsync(applicationUser, loginModel.Password, false, false)).Succeeded)
return true;
return false;
public async Task LogOut()
await _signInManager.SignOutAsync();
public async Task<string> SignUp(LoginModel loginModel)
IdentityUser applicationUser = new IdentityUser()
UserName = loginModel.Name,
Email = loginModel.Email
Employee em = _employeeRepository.GetEmployee(e => e.Email == loginModel.Email);
if (em == null)
return "Opgegeven email adres niet bekend";
if (em.LabelId == loginModel.LabelId && em.Name == loginModel.EmployeeName)
var result = await this._userManager.CreateAsync(applicationUser, loginModel.Password);
if (result.Succeeded)
IdentityUser createUser =
this._userManager.Users.FirstOrDefault(u => u.Email.Equals(loginModel.Email));
return "Success";
foreach (var error in result.Errors)
return "Geen geldige registratie gegevens.";
return "Opgegeven naam en id zijn niet kloppend bij het email adres.";
return "Er is iets misgegaan tijdens de registratie";
DBEmployeeRepository
public class DBEmployeeRepository : IEmployeeRepository
private EmployeeCollection employeeCollection;
private readonly DbContextOptions<AppDbContext> _contextOptions;
public DBEmployeeRepository(DbContextOptions<AppDbContext> contextOptions)
_contextOptions = contextOptions;
using (var context = new AppDbContext(_contextOptions))
employeeCollection = new EmployeeCollection()
AllEmployees = context.Employees
.Include("Contacts.Contact")
.Include("Deals.EmployeeDeal")
.Include("Label.Label")
.ToList()
public Employee GetEmployee(Func<Employee, bool> lambda)
Employee employee = employeeCollection.AllEmployees.FirstOrDefault(lambda);
return employee;
public IEnumerable<Employee> GetEmployees()
return employeeCollection.AllEmployees;
public IEnumerable<Employee> GetEmployees(Func<Employee, bool> lambda)
return employeeCollection.AllEmployees.Where(lambda);
Startup.cs
public class Startup
public Startup(IConfiguration configuration)
Configuration = configuration;
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
services.Configure<CookiePolicyOptions>(options =>
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
Configuration["Data:Project:ConnectionString"]));
services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(
Configuration["Data:Identity:ConnectionString"]));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppIdentityDbContext>()
.AddDefaultTokenProviders();
services.AddScoped<IEmployeeRepository, DBEmployeeRepository>();
services.AddScoped<ICompanyRepository, DBCompanyRepository>();
services.AddScoped<IContactRepository, DBContactRepository>();
services.AddScoped<IDealRepository, DBDealRepository>();
services.AddScoped<IInvoiceRepository, DBInvoiceRepository>();
services.AddScoped<ILabelRepository, DBLabelRepository>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
IdentitySeedData.EnsurePopulated(app);
app.UseCookiePolicy();
app.UseMvc(routes =>
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Login}/{id?}");
You neglected to register LoginManager
with your services.
services.AddScoped<LoginManager>();
Since you're a student, there are some pretty serious code issues here you should be aware of. First, your repository is entirely wrong. You should pretty much never use using
with a context, as it should remain request scoped. You should also not do something like query a database in a class constructor. Doing this is problematic regardless, though, as your capturing the data only at instantiation. If you go on to add additional instances of your entity to the database, your repo will not reflect that. Instead, you should inject your context into your repo's constructor, save it to a readonly ivar, and then utilize it directly in your repo methods.
That said, using the repository pattern here at all is a mistake. The point of the repository pattern is to abstract low-level database access (SQL query strings and such) out of your application code. When using an ORM like Entity Framework, that's already been done for you. In fact, DbContext
implements the Unit of Work pattern and each DbSet
on it is a repository. When using an ORM, that is your data layer; creating your own data layer that wraps that is redundant and only serves to increase the entropy of your code.
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.