Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get instance from Ninject

Below is NinjectHttpApplication configuration..

public class MvcApplication : NinjectHttpApplication
{
        public MvcApplication()
        {
            Error += NinjectWebsiteApplication_Error;
        }
}    

protected override IKernel CreateKernel()
{
        var kernel = new StandardKernel();
        kernel.Load<ApplicationConfig>();
        return kernel;
}

void NinjectWebsiteApplication_Error(object sender, System.EventArgs e)
{
        ILogger _iLogger = **//How to get instance of Applogger here from Ninject kernel..**
}

Below is the ApplicationConfig class...

public class ApplicationConfig : NHibernateNinjectModule
{

    public ApplicationConfig()
    {
     //other settings such as ddl script generation is present here
    }
    public override void Load()
    {                
        base.Load();
        Bind<ILogger>().To<AppLogger>().InSingletonScope();
    }
}
like image 474
Sunny Avatar asked Oct 04 '12 13:10

Sunny


1 Answers

void NinjectWebsiteApplication_Error(object sender, System.EventArgs e)
{
     var kernel = CreateKernel();
     ILogger _iLogger = kernel.Get<ILogger>();
}

Ok, as it seems NinjectHttpApplication stores generated kernel object in

public IKernel Kernel
{
    get { return _kernel; }
}

So you could rewrite above as

void NinjectWebsiteApplication_Error(object sender, System.EventArgs e)
{
     ILogger _iLogger = Kernel.Get<ILogger>();
}
like image 75
archil Avatar answered Oct 11 '22 14:10

archil