如何修复.NET Core中Startup.cs类中的依赖项注入错误

时间:2019-03-11 07:45:31

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

我使用ASP.NET Core 2.2 我试图从启动中调用基本服务类。引发此异常:

  

InvalidOperationException:无法解析类型的服务   尝试激活时出现“ TIR.NetCore.ICommonLogService”   “ AdminCentral.NetCore.Startup”。

这是我的代码:

public class Startup
{
    private readonly ICommonLogService _CommonLogService;
    public Startup(IConfiguration configuration, ICommonLogService CommonLogService)
    {
         _CommonLogService = CommonLogService;
         Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    public string connectionString;

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        var container = new Container();
        container.Configure(config =>
        {
            config.AddRegistry(new StructuremapRegistry());
            config.Populate(services);
        });

        return container.GetInstance<IServiceProvider>();
    }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      LogException(Exception )
   }

    private void LogException(Exception error, HttpContext context)
    {
         _CommonLogService.InsertLogDetail();
  }
}

1 个答案:

答案 0 :(得分:1)

如果要在启动类中使用ICommonLogService,则需要从容器中获取一个实例,如下所示:

public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        var container = new Container();
        container.Configure(config =>
        {
            config.AddRegistry(new StructuremapRegistry());
            config.Populate(services);
        });

        //Get an instance of ICommonLogService from container
        ICommonLogService CommonLogService = container.GetInstance<ICommonLogService>();
        //Use CommonLogService here

        return container.GetInstance<IServiceProvider>();
    }