【问题标题】:InvalidOperationException: Unable to resolve service for type 'IDocumentService' while attempting to activate 'DocumentController'InvalidOperationException:尝试激活“DocumentController”时无法解析“IDocumentService”类型的服务
【发布时间】:2021-02-23 18:47:46
【问题描述】:

现在我正在开发 Web api Asp.net 核心,但我对 DI 感到困惑。 当我尝试向我的 api 发送请求时,出现此错误

我使用 Ninject,我认为我对此有疑问 GitLab 和我的项目https://gitlab.com/ValeriiDmytryshyn/sharedocument

启动文件可能有问题

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.AddDbContext<DocumentContext>
            (options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

        services.AddControllers();
        var mappingConfig = new MapperConfiguration(mc =>
        {
            mc.AddProfile(new AutomapperProfile());
        });

        IMapper mapper = mappingConfig.CreateMapper();
        services.AddSingleton(mapper);

        services.AddMvc();

        NinjectModule ninjectModule = new NinjModule();
        NinjectModule serviceModule = new ServiceModule(Configuration["ConnectionStrings:DefaultConnection"]);
        var kernel = new StandardKernel(ninjectModule, serviceModule);
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }


    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseDeveloperExceptionPage();

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

【问题讨论】:

  • 好的对不起我会编辑它

标签: c# api asp.net-web-api


【解决方案1】:

看来您需要为依赖注入注册服务才能解析您的类。

您必须将所有注入的类注册为 Singleton 或 Transient。这是在 startup.cs 中尝试的示例

services.AddTransient<IDocumentService , DocumentService>();

有关详细信息,请参阅文档 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0

【讨论】:

  • 我不知道我需要注册什么我会读码头但现在我试着做一些这样的想法并有这个例外ibb.co/ZNLVBVZ
  • 是的,谢谢,我做了 services.AddTransient(); services.AddTransient(); services.AddTransient();在 Startup 中,并更改了 UnitOfWork 构造函数
猜你喜欢
  • 2020-02-08
  • 2021-04-29
  • 2020-07-01
  • 2020-05-18
  • 2018-06-08
  • 2018-07-07
  • 2019-08-21
  • 2020-08-21
  • 1970-01-01
相关资源
最近更新 更多