Tester User
Tester User

Reputation: 225

C# :Unity container and ILogger

I'm working on ASP .Net MVC5 project, I'm using ILogger interface inder Microsoft.Extensions.Logging and Unity framework for DI.

What I want is to inject ILogger into my project to use it in my controllers.

I installed Unity and Unity.MVC nuget packages in my project and I tried to inject ILogger like this :

 public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType(typeof(ILogger<>), typeof(Logger<>), (new HierarchicalLifetimeManager()));
        }

My controller :

public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger logger)
        {
            _logger = logger;
        }
        public ActionResult Index()
        {
            _logger.LogInformation("TEST log event message");

            return View();
        }

Always when I run the project I get this error :

Project exception error

Upvotes: 2

Views: 3521

Answers (1)

Sean M
Sean M

Reputation: 626

You registered ILogger<T> but your HomeController expects ILogger. Unity container is trying to build an ILogger; it is an interface so it has no public ctor.

Change your HomeController ctor to this to make your registrations work...

public HomeController(ILogger<HomeController> logger)

Upvotes: 3

Related Questions