在一个解决方案中的两个项目中使用Ninject,出现循环依赖异常
本文关键字:Ninject 依赖 异常 循环 两个 解决方案 一个 项目 | 更新日期: 2023-09-27 18:21:28
我在同一解决方案中的两个项目中使用Ninject。在具有视图和Web.API项目的MVC中。但当我尝试同时运行两个项目时,Web API NinjectWebCommon.cs
出现以下异常-
使用来自的绑定激活ModelValidatorProvider时出错ModelValidatorProvider到NinjectDefaultModelValidatorProviderA在两个的构造函数之间检测到循环依赖关系服务。
但若我只运行Web API项目,就不会遇到上面提到的异常。我在两个项目中都有NinjectWebCommon.cs
文件。
网络API-
public static void Start() //The method looks the same for MVC Project
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
WebIoC.RegisterServices(kernel);
}
和MVC项目-
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
RegisterServiceLocator(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServiceLocator(StandardKernel kernel)
{
var locator = new NinjectServiceLocator(kernel);
ServiceLocator.SetLocatorProvider(() => locator);
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFormsAuthenticationService>().To<FormsAuthenticationService>();
kernel.Bind<IAdMembershService>().To<ActiveDirectoryMembershipService>();
kernel.Bind<IFacebookAuthenticationService>().To<FacebookAuthenticationService>();
}
我在Start()
方法中的bootstrapper.Initialize(CreateKernel);
中遇到此异常。有人遇到过同样的问题吗?
更新:如果重要的话,我还在两个项目中使用以下代码启动。
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Path.to.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Path.to.NinjectWebCommon), "Stop")]
这种情况以前也发生过,请参阅Ninject Issue 131。
Arindamat提出了以下解决方案:
_kernel
.Bind<DefaultModelValidatorProviders>()
.ToConstant(new DefaultModelValidatorProviders(
config.Services.GetServices(
typeof (ModelValidatorProvider))
.Cast<ModelValidatorProvider>()));
从而消除了循环依赖性。
然而,的根本原因通常是ninject安装失败。这个答案显示了如何修复它。