如何从Ninject获取实例

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

最佳答案

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

关于asp.net-mvc - 如何从Ninject获取实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12728945/

10-13 01:34