【问题标题】:Unable to resolve service for type while attempting to activate尝试激活时无法解析服务类型
【发布时间】:2018-04-06 09:44:27
【问题描述】:

在我的 ASP.NET Core 应用程序中,我收到以下错误:

InvalidOperationException:尝试激活“Cities.Controllers.HomeController”时无法解析“Cities.Models.IRepository”类型的服务。

我是 HomeController 我正在尝试将 Cities getter 传递给视图,如下所示:

public class HomeController : Controller
{
    private readonly IRepository repository;

    public HomeController(IRepository repo) => repository = repo;

    public IActionResult Index() => View(repository.Cities);
}

我有一个文件Repository.cs,其中包含一个接口及其实现,如下所示:

public interface IRepository
{
    IEnumerable<City> Cities { get; }
    void AddCity(City newCity);
}

public class MemoryRepository : IRepository
{
    private readonly List<City> cities = new List<City>();

    public IEnumerable<City> Cities => cities;

    public void AddCity(City newCity) => cities.Add(newCity);
}

我的Startup 类包含模板中默认生成的代码。我做了任何更改:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...
    }
}

【问题讨论】:

    标签: c# asp.net-core dependency-injection asp.net-core-mvc


    【解决方案1】:

    要让依赖注入框架解析IRepository,它必须首先向容器注册。例如,在ConfigureServices 中,添加以下内容:

    services.AddScoped<IRepository, MemoryRepository>();
    

    对于默认使用 new hosting model 的 .NET 6+,请在 Program.cs 中添加以下内容:

    builder.Services.AddScoped<IRepository, MemoryRepository>();
    

    AddScoped 只是service lifetime 的一个例子:

    对于 Web 应用程序,范围生命周期表示每个客户端请求(连接)创建一次服务。

    有关 ASP.NET Core 中的依赖注入的更多信息,请参阅docs

    【讨论】:

      【解决方案2】:

      我们在实体框架工作核心数据库优先方法中遇到此错误。我按照以下步骤解决了错误enter code here

      第 1 步:检查您的上下文类构造函数应该是这样的

      public partial class ZPHSContext : DbContext
      {
          public ZPHSContext(DbContextOptions<ZPHSContext> dbContextOptions)
              : base(dbContextOptions)
          {
          }
      }
          
      

      第 2 步:在启动文件中

      public void ConfigureServices(IServiceCollection services)
      {
          services.AddMvc();
          services.AddDbContext<ZPHSContext>(options =>
              options.UseSqlServer(
                  Configuration.GetConnectionString("BloggingDatabase")));
      }
          
      

      第 3 步:appsettings 中的连接字符串

      "ConnectionStrings": {
          "BloggingDatabase": "Server=****;Database=ZPHSS;Trusted_Connection=True;"
      }
      

      第 4 步:删除上下文类中 OnConfiguring 方法中的默认代码

      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
      }
      

      【讨论】:

        【解决方案3】:

        其他答案是正确的,但是我正在启动一个新的 asp.net core 2.1.x 项目并收到此错误。

        最后被我打错了。

        所以在我的控制器中而不是正确使用这样的界面

        public HomeController(IApplicationRepository applicationRepository)
        {
            _applicationRepository = applicationRepository;
        }
        

        我的错字让我使用ApplicationRepository 而不是它的界面IApplicationRepository 请注意下面,因此没有错误发现丢失的“我”很有趣:/

        public HomeController(IApplicationRepository applicationRepository)
        {
            _applicationRepository = applicationRepository;
        }
        

        因此控制器没有解析 DI...

        【讨论】:

        • 我……我不敢相信这是我的问题。正是我的问题。好痛苦……谢谢!
        • 不行!这也是我的问题!
        【解决方案4】:

        这样的方法需要添加到您的Startup

            // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //...
        
            // Add application services.
            services.AddTransient<IRepository, MemoryRepository>();
        
            //..
        }
        

        服务应在使用前注册。

        更新: 如果您不想在应用程序中使用 DI,只需在 HomeController 的构造函数上创建 MemoryRepository 的实例,如下所示:

        public class HomeController : Controller
            {
                private IRepository repository;
        
                public HomeController()
                {
                    repository = new MemoryRepository();
                }
        
                public IActionResult Index()
                {
                    return View(repository.Cities);
                }
        
            }
        

        【讨论】:

        • 如何在不使用 DI 的情况下修改我现有的代码?
        【解决方案5】:

        您必须将您的实现添加到 DI(依赖注入)部分。对于 .Net Core Mvc,应该是这样的:

         public void ConfigureServices(IServiceCollection services)
         {
           services.AddDbContext<ApplicationDbContext>(options =>
            options.UseInMemoryDatabase()
           );
           services.AddScoped<IRepository, MemoRepostory>();
        
         }
        

        【讨论】:

          【解决方案6】:

          这可能对您的代码示例没有帮助,但在我的情况下,同样的错误是循环依赖的结果。

          【讨论】:

            【解决方案7】:

            你必须像这样注册你的存储库

            services.AddSingleton&lt;IRepository, MemoryRepository&gt;();

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-03-23
              • 1970-01-01
              • 2020-04-22
              • 2021-12-25
              • 2018-09-24
              相关资源
              最近更新 更多