如何从Ninject获取实例

时间:2012-10-04 13:58:21

标签: asp.net-mvc ninject

以下是NinjectHttpApplication配置..

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..**
}

以下是ApplicationConfig类......

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();
    }
}

1 个答案:

答案 0 :(得分:4)

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

好的,似乎NinjectHttpApplication将生成的内核对象存储在

public IKernel Kernel
{
    get { return _kernel; }
}

所以你可以在上面改写为

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