1

I have ASP.NET MVC 5 application with Owin.

This is my interface:

using System.Collections.Generic;

namespace MvcApp.Logging
{
    public interface ILog
    {
        void Debug(string format, params object[] args);
        void Error(string format, params object[] args);
        void Fatal(string format, params object[] args);
        void Info(string format, params object[] args);
        void Trace(string format, params object[] args);
        void Warn(string format, params object[] args);

        // custom
        void Write(LogType type, object properties, string message, params object[] args);

        bool IsDebugEnabled { get; }
        bool IsErrorEnabled { get; }
        bool IsFatalEnabled { get; }
        bool IsInfoEnabled { get; }
        bool IsTraceEnabled { get; }
        bool IsWarnEnabled { get; }
    }
}

I'm using the nuget package Autofac.Mvc5.Owin to inject ILog into the constructor of the controller. This approach it works perfectly.

Owin Startup Class:

builder.RegisterType<Log>().As<ILog>().InstancePerRequest();

Now I need inject ILog interface into Global.asax.cs class and Application_Start method.

Is this possible? What do I need to setup for inject ILog?

public class MvcApplication : HttpApplication
{
   // How to inject ILog here?

    protected void Application_Start()
    {
       // I need write for example this message
       ILog.Info("Application starting");
    }
}

Thanks a lot

ericardezp
  • 29
  • 1
  • 6
  • "Application start" -> this is where you make the app initialization it is the same as your application startup class... – Legends Oct 19 '16 at 02:59
  • IMHO, if your app requested to database context, put it on `Application_BeginRequest` or `Application_AuthenticateRequest`, since `Application_Start` doesn't contain `HttpContext` instance. – Tetsuya Yamamoto Oct 19 '16 at 03:32

1 Answers1

0

The Application_Start method in Global.asax runs before Owin Startup.Configuration. So even if you would find a way to inject ILog interface to the Application_Start method the interface would not have been resolved at that time.

Instead of using the ILog in Application_Start method, use it in the Owin Startup.Configuration method after the dependencies has been resolved.

Here's a great SO question about Global.asax vs Owin Startup which is a good read

Community
  • 1
  • 1
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69