Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to inject ILogger into MvcApplication (asp.net mvc) #14

Closed
programatt opened this issue Sep 19, 2012 · 3 comments
Closed

Unable to inject ILogger into MvcApplication (asp.net mvc) #14

programatt opened this issue Sep 19, 2012 · 3 comments

Comments

@programatt
Copy link

I'm using ninject.extensions.logging and ninject.extensions.log4net. I can confirm I have logging setup properly because all my controllers/other classes in the project are able to log. But for some reason I can't get ninject to inject an ILogger into the MvcApplication class in the global asax file. Here's the code

public class MvcApplication : System.Web.HttpApplication
{
    [Inject]
    public ILogger logger { get; set; }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        log4net.Config.XmlConfigurator.Configure();

        //Tell the world we started up!
        logger.Info("Application Started Successfully!");
    }

    protected void Application_Error()
    {
        var error = Server.GetLastError();
        logger.Error(error,"Unhandled Exception In Web Application",new object[]{});
    }
}

as you can see the ILogger is being injected with the [Inject] attribute as a property. But I always get a null reference when I try and use it from inside this class.

@idavis
Copy link
Member

idavis commented Sep 19, 2012

I'm not familiar with how MvcApplication gets activated, but I don't think
Ninject actually creates this class, and thus does not inject a logger. Can
anyone verify?

-Ian

On Tue, Sep 18, 2012 at 8:43 PM, Matt Phillips notifications@github.comwrote:

I'm using ninject.extensions.logging and ninject.extensions.log4net. I can
confirm I have logging setup properly because all my controllers/other
classes in the project are able to log. But for some reason I can't get
ninject to inject an ILogger into the MvcApplication class in the global
asax file. Here's the code

public class MvcApplication : System.Web.HttpApplication
{
[Inject]
public ILogger logger { get; set; }

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

}

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    log4net.Config.XmlConfigurator.Configure();

    //Tell the world we started up!
    logger.Info("Application Started Successfully!");
}

protected void Application_Error()
{
    var error = Server.GetLastError();
    logger.Error(error,"Unhandled Exception In Web Application",new object[]{});
}

}

as you can see the ILogger is being injected with the [Inject] attribute
as a property. But I always get a null reference when I try and use it from
inside this class.


Reply to this email directly or view it on GitHubhttps://github.com//issues/14.

@programatt
Copy link
Author

I'm also using the Ninject.Mvc3 package. That package creates the following class.

[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(Web.App_Start.NinjectWebCommon), "Stop")]

namespace Web.App_Start
{
public static class NinjectWebCommon 
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
             //my registrations in here
    }        
}
}

Even with the ninject.extensions.logging.log4net package installed that doesn't change this class. So #1 I have no idea how it's hooking up the logging internally, #2 I don't know if there's even a way to alter it because it happens behind the scenes

@programatt
Copy link
Author

I ended up finding a stackoverflow question that answered mine. I don't have the link for it, but I think it just has something to do with how the MVC3 plugin automagically adds the ninject module after the application is started. I was able to solve this by using var logger = DependencyResolver.Current.GetService<ILogger>(); (which i didn't know existed).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants