Solving error - Unable to resolve service for type 'Serilog.ILogger'

Sanket picture Sanket · Nov 20, 2016 · Viewed 20.3k times · Source

I am trying to implement SeriLog in ASP.NET core application (.NET framework)

Below are steps I performed so far-

1) Added below references in Project.json

"Serilog": "2.2.0",
"Serilog.Extensions.Logging": "1.2.0",
"Serilog.Sinks.RollingFile": "2.0.0",
"Serilog.Sinks.File": "3.0.0"

2) Added following lines to the constructor of your Startup class-

Log.Logger = new LoggerConfiguration()
           .MinimumLevel.Debug()
           .WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "log-{Date}.txt"))
           .CreateLogger();

3) Added following line to the configure method of your Startup class-

loggerFactory.AddSerilog();

4) Injecting the logger to HomeController like this-

ILogger logger;

    public HomeController(ILogger logger)
    {
        this.logger = logger;
    }

5) In About action, trying to log exception like this-

public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        try
        {
            throw new Exception("Serilog Testing");
        }
        catch (System.Exception ex)
        {
            this.logger.Error(ex.Message);
        }

        return View();
    }

On running my application, I am getting below error-

System.InvalidOperationException: Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'AspNetCore_SeriLog_trial1.Controllers.HomeController'. at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.Mvc.Internal.TypeActivatorCache.CreateInstance[TInstance](IServiceProvider serviceProvider, Type implementationType) at Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerActivator.Create(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__26.MoveNext()

Could anyone please help me on this? Any configuration missing for Serilog?

Answer

dotnetstep picture dotnetstep · Nov 20, 2016

Try to do following thing in your controller.

    ILogger<HomeController> logger = null;
    public HomeController(ILogger<HomeController> _logger)
    {
        logger = _logger;
    }