Unable to resolve service for type in ApplicationDbContext

10,945

Solution 1

DI would not have been setup via command line, which is why you are getting the above exception.

In the comments you explain that you want access to the HttpContext via IHttpContextAccessor which is something that is usually available at run time.

Migrations are not applied at run time, where DI would have been configured and available.

You may need to read up on Configuring a DbContext. This documentation is for EF7 onwards

Solution 2

I found this forum that led me to the following solution: https://github.com/aspnet/EntityFrameworkCore/issues/4232

Create a new service class and interface:

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

And register it with your DI container (Startup.cs for example)

    services.AddTransient<IUserResolverService, UserResolverService>();

Then in your DbContext, use the userResolverService to get the username instead of IHTTPContextAccessor

    private readonly IUserResolverService userResolverService;
    public ApplicationDbContext(IUserResolverService userResolverService) : base()
    {
        this.userResolverService = userResolverService;

        var username = userResolverService.GetCurrentUser();
...
Share:
10,945

Related videos on Youtube

Yurii N.
Author by

Yurii N.

Updated on June 15, 2022

Comments

  • Yurii N.
    Yurii N. over 1 year

    When I'm trying to add migrations with dnx ef migrations add Mig, I have the following exception in console:

    Unable to resolve service for type 'Microsoft.AspNet.Http.IHttpContextAcccessor' while attempting to activate 'NewLibrary.Models.ApplicationDbContext'.

    My ApplicationDbContext:

    public class ApplicationDbContext : DbContext
    {
        private readonly IHttpContextAccessor _accessor;
    
        public ApplicationDbContext(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
    }
    

    What's the problem?

    How should I correctly add dependencies to ApplicationDbContext constructor?

    • Nkosi
      Nkosi over 7 years
      Why would your DbContext need a dependency on IApplicationBuilder. I'm just curious.
    • Nkosi
      Nkosi over 7 years
      My question still applies, now just for IHttpContextAccessor. You seem to be mixing concerns given the information you provided
    • Nkosi
      Nkosi over 7 years
      Which exists during migration? Is HttpContext available at that point?
    • Nkosi
      Nkosi over 7 years
      Is the migration happening at runtime or via command line?
    • Nkosi
      Nkosi over 7 years
      As expected. Migration is not done at run time, where DI would have been configured and available. DI would not have been setup via command line, which is why you are getting the above exception.
  • Yurii N.
    Yurii N. over 7 years
    Your link Setting up connection strings and dependency injection refers to Entity Framework 6. Is this applied to EF Core? What about migrations, if we register context as service, not via AddEF() extension in Startup.cs?
  • Nkosi
    Nkosi over 7 years
    Apologies I was researching both versions. will update with EF Core link
  • Yurii N.
    Yurii N. over 7 years
    I have found the solution, just to put all in OnConfiguring into try-catch block, so, when you apply migrations, no exceptions will throw via command line.
  • Nkosi
    Nkosi over 7 years
    Glad you found a solution.
  • patrickbadley
    patrickbadley over 5 years
    @YuriyN. Edited my answer to make it more clear. Use userResolverService in your DbContext class to get the username. Hope that helps!