我正在使用MVC 4.0& .net 4.0并希望使用Ninject。
我有一个静态类,其中创建了对象。我不能使静态调用类非静态!
我正在尝试基于此绑定获取实例
Bind<ClinicWebsite.ViewModels.ISelectionEngine>)
.To<ClinicWebsite.ViewModels.Genric_SelectionEngine>();
我在静态类中调用:
ClinicWebsite.ViewModels.Generic_SelectionEngine myService =
ClinicWebsite.App_Start.NinjectWebCommon.Kernel
.GetService(typeof(ClinicWebsite.ViewModels.ISelectionEngine))
as ClinicWebsite.ViewModels.Generic_SelectionEngine;
但是当我检查“myservice”时,我得到了:
The name 'myservice' does not exist in the current context
我可能做错了什么,或者是否有其他方法使用Ninject显式创建实例(再次,无法摆脱静态调用类)
NinjectWebCommon
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
private static readonly StandardKernel kernel = new StandardKernel();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
//DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
Bind<ClinicWebsite.ViewModels.ISelectionEngine>().To<ClinicWebsite.ViewModels.Generic_SelectionEngine>();
}
public static IKernel Kernel
{
get
{
return kernel;
}
}
}
答案 0 :(得分:0)
我找到了答案。 因为这是一个静态的课程,我需要制作&#34; myservice&#34;该类的静态成员,然后分配给它。