我有以下NinjectModule,我们绑定了我们的存储库和业务对象:
/// <summary>
/// Used by Ninject to bind interface contracts to concrete types.
/// </summary>
public class ServiceModule : NinjectModule
{
/// <summary>
/// Loads this instance.
/// </summary>
public override void Load()
{
//bindings here.
//Bind<IMyInterface>().To<MyImplementation>();
Bind<IUserRepository>().To<SqlUserRepository>();
Bind<IHomeRepository>().To<SqlHomeRepository>();
Bind<IPhotoRepository>().To<SqlPhotoRepository>();
//and so on
//business objects
Bind<IUser>().To<Data.User>();
Bind<IHome>().To<Data.Home>();
Bind<IPhoto>().To<Data.Photo>();
//and so on
}
}
以下是我们的Global.asax的相关覆盖,我们从NinjectHttpApplication继承,以便将它与Asp.Net Mvc集成(该模块位于一个名为Thing.Web.Configuration的独立DLL中):
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
//routes and areas
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
//Initializes a singleton that must reference this HttpApplication class,
//in order to provide the Ninject Kernel to the rest of Thing.Web. This
//is necessary because there are a few instances (currently Membership)
//that require manual dependency injection.
NinjectKernel.Instance = new NinjectKernel(this);
//view model factory.
NinjectKernel.Instance.Kernel.Bind<IModelFactory>().To<MasterModelFactory>();
}
protected override NinjectControllerFactory CreateControllerFactory()
{
return base.CreateControllerFactory();
}
protected override Ninject.IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load("Thing.Web.Configuration.dll");
return kernel;
}
现在,一切都很好,但有一个例外:出于某种原因,有时Ninject会将PhotoController 绑定两次。这会导致ActivationException,因为Ninject不能辨别我想要哪个PhotoController。这会导致站点上的缩略图和其他用户图像的所有请求失败。
以下是PhotoController的全部内容:
public class PhotoController : Controller
{
public PhotoController()
{
}
public ActionResult Index(string id)
{
var dir = Server.MapPath("~/" + ConfigurationManager.AppSettings["UserPhotos"]);
var path = Path.Combine(dir, id);
return base.File(path, "image/jpeg");
}
}
每个控制器的工作方式完全相同,但由于某种原因,PhotoController会受到双重约束。即便如此,它只会偶尔发生(无论是重新构建解决方案,还是在应用程序池启动时进行暂存/生产)。一旦发生这种情况,它将继续发生,直到我重新部署而不改变任何东西。
那么......那是怎么回事?
答案 0 :(得分:2)
如your answer to another similar question的评论中所述,这是Ninject 2.0中的竞争条件错误,已在2.2版中修复。我找不到Ninject的任何发行说明,但它为我解决了这个问题。