2

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

1
  • 6
    You only registered the generic version of ILogger<> while your controller is expecting the non-generic version. Did you try to simply register Logger as ILogger? Commented Mar 11, 2019 at 14:34

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.