简体   繁体   中英

How to fix the Dependency Injection error in Startup.cs class in .NET Core

I use ASP.NET Core 2.2 I am trying to call a basic service class from Startup. It is throwing this exception:

InvalidOperationException: Unable to resolve service for type 'TIR.NetCore.ICommonLogService' while attempting to activate 'AdminCentral.NetCore.Startup'.

This my code:

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();
  }
}

If you want to use ICommonLogService in the Startup.cs class, you need to get an instance from the container like this:

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>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM