我在Ninject的bootstap中有这个代码:
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
//TODO: Enregistrer les services ici.. pour ninject!
kernel.Bind<IContext>().To<MySampleContext>();
kernel.Bind<ISampleService>().To<SampleService>();
}
在我的全球范围内,我试试这个..
protected virtual void Application_BeginRequest()
{
ContextProvider cp = new ContextProvider();
DbContext context = (DbContext)DependencyResolver.Current.GetService<IContext>();
cp.SetCurrent(context);
}
编辑:这里是完整的引导程序......但它是ninjectt附带的基本引导程序。
public static class NinjectMVC3
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
//TODO: Enregistrer les services ici.. pour ninject!
kernel.Bind<IContext>().To<MySampleContext>();
kernel.Bind<ISampleService>().To<SampleService>();
}
}
但它返回NULL?为什么?