简体   繁体   English

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

[英]Unable to resolve service for type while attempting to activate

In my ASP.NET Core application, I get the following error:在我的 ASP.NET Core 应用程序中,出现以下错误:

InvalidOperationException: Unable to resolve service for type 'Cities.Models.IRepository' while attempting to activate 'Cities.Controllers.HomeController'. InvalidOperationException:尝试激活“Cities.Controllers.HomeController”时无法解析类型“Cities.Models.IRepository”的服务。

I the HomeController I am trying to pass the Cities getter to the view like so:我是HomeController ,我正在尝试将Cities getter 传递给视图,如下所示:

public class HomeController : Controller
{
    private readonly IRepository repository;

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

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

I have one file Repository.cs that contains an interface and its implementation like so:我有一个文件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);
}

My Startup class contains the default-generated code from the template.我的Startup class 包含模板中默认生成的代码。 I have made any changes:我做了任何改变:

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

For the Dependency Injection framework to resolve IRepository , it must first be registered with the container.为了让依赖注入框架解析IRepository ,它必须首先在容器中注册。 For example, in ConfigureServices , add the following:例如,在ConfigureServices ,添加以下内容:

services.AddScoped<IRepository, MemoryRepository>();

AddScoped is just one example of a service lifetime : AddScoped只是服务生命周期的一个例子:

For web applications, a scoped lifetime indicates that services are created once per client request (connection).对于 Web 应用程序,范围生命周期表示每个客户端请求(连接)创建一次服务。

See the docs for more information on Dependency Injection in ASP.NET Core.有关 ASP.NET Core 中的依赖注入的更多信息,请参阅文档

We are getting this error in Entity frame work core database first approach.我们在实体框架核心数据库第一种方法中遇到此错误。 I followed below steps and error got resolved enter code here我按照以下步骤操作,错误得到解决,请enter code here

Step 1: Check Your context class constructor should be like this第 1 步:检查您的上下文类构造函数应该是这样的

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

Step 2: In Startup file第 2 步:在启动文件中

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

Step 3: Connection string in appsettings第 3 步:appsettings 中的连接字符串

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

Step 4: Remove default code in OnConfiguring method in context class第 4 步:删除上下文类中 OnConfiguring 方法中的默认代码

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}

A method like this needs to be added to your Startup :需要将这样的方法添加到您的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>();

    //..
}

Services should be registered before used.服务应在使用前进行注册。

UPDATE: If you do not want to use DI on your application, just create and instance of MemoryRepository on the constructor of HomeController , like this:更新:如果您不想在应用程序上使用 DI,只需在HomeController的构造函数上创建MemoryRepository实例,如下所示:

public class HomeController : Controller
    {
        private IRepository repository;

        public HomeController()
        {
            repository = new MemoryRepository();
        }

        public IActionResult Index()
        {
            return View(repository.Cities);
        }

    }

Other answers are CORRECT, however I was spinning up a new asp.net core 2.1.x project and got this error.其他答案是正确的,但是我正在启动一个新的 asp.net core 2.1.x 项目并收到此错误。

Ended up being a typo by ME.最终被我打错了。

So in my Controller instead of Correctly using the Interface like this所以在我的控制器中而不是像这样正确使用接口

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

My typo had me using ApplicationRepository instead of its interface IApplicationRepository Notice below, and so with NO ERRORS spotting the missing "I" was fun :/我的错字让我使用ApplicationRepository而不是它的接口IApplicationRepository通知如下,因此没有错误发现丢失的“I”很有趣:/

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

Thus the controller was not resolving the DI...因此控制器没有解决 DI...

You have to add your implementation to DI (Dependeny Injection) section.您必须将您的实现添加到 DI(依赖注入)部分。 For .Net Core Mvc, it would be like this:对于 .Net Core Mvc,它会是这样的:

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

 }

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

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

services.AddSingleton<IRepository, MemoryRepository>();

In my case, I was trying to access context through constructor.就我而言,我试图通过构造函数访问上下文。 like here;像这儿;

 private readonly Context _context;

 public ImageController(Context context)
 {
    _context = context;
 }

But When I tried to access the context just by creating an instance of class, it worked like here;但是当我试图通过创建 class 的实例来访问上下文时,它就像这里一样工作;

 Context c = new Context();

For me I am using visual studio 2022 and .NET 6对我来说,我使用的是 Visual Studio 2022 和 .NET 6

the solution was add the following line in the Program.cs file:解决方案是在 Program.cs 文件中添加以下行:

builder.Services.AddSingleton<IHISInterface<UserDetails>, UserDetailsRepository>();

There is one more possibility that, You might have sent wrong variable in the place while writing this HTTPPOST last part code还有一种可能性,您可能在编写此 HTTPPOST 最后一部分代码时在该位置发送了错误的变量

mine is我的是

var categoryMap = _mapper.Map(categoryCreate); var categoryMap = _mapper.Map(categoryCreate);

        if(!_categoryRepository.CreateCategory(categoryMap))
        {
            ModelState.AddModelError("", "Something went wrong while saving");
            return StatusCode(500, ModelState);
        }
        return Ok("Successfully created");

in the if condition I passed the category as parameter instead of categoryMap在 if 条件下,我将类别作为参数而不是categoryMap传递

so please cross check所以请交叉检查

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试激活“”时无法解析“”类型的服务 - Unable to resolve service for type '' while attempting to activate '' InvalidOperationException:尝试激活“UnitOfWork”时无法解析“DataAccessContext”类型的服务 - InvalidOperationException: Unable to resolve service for type 'DataAccessContext' while attempting to activate 'UnitOfWork' 依赖注入错误-尝试激活时无法解析服务…的类型 - Dependeny Injection Error - Unable to resolve service … for type while attempting to activate System.InvalidOperationException:尝试激活时无法解析服务类型 - System.InvalidOperationException: Unable to resolve service for type while attempting to activate 尝试激活页面 model 时无法解析类型 [DBcontext] 的服务 - Unable to resolve service for type [DBcontext] while attempting to activate page model 依赖注入错误在尝试激活时无法解析类型的服务 - Dependeny Injection Error Unable to resolve service for type while attempting to activate InvalidOperationException:尝试激活“DocumentController”时无法解析“IDocumentService”类型的服务 - InvalidOperationException: Unable to resolve service for type 'IDocumentService' while attempting to activate 'DocumentController' .net Core 6 - 尝试激活时无法解析服务类型 - .net Core 6 - Unable to resolve service for type while attempting to activate 尝试激活功能时无法解析服务类型 - Unable to resolve service for type while attempting to activate function 管理个人资料页面:尝试激活时无法解析服务类型 - Manage Profile page: Unable to resolve service for type while attempting to activate
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM