【发布时间】:2011-01-06 19:51:08
【问题描述】:
我有以下 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 会被双重绑定。即使这样,它也只是偶尔发生(在重新构建解决方案时,或者在应用程序池启动时的暂存/生产中)。一旦发生这种情况,它会继续发生,直到我重新部署而不做任何更改。
那么...这是怎么回事?
【问题讨论】:
-
从未发现发生这种情况的原因。我最终用通用处理程序替换了这种访问图像的方法,从 Azure Blob 存储中提供内容。
-
不过,我有一个理论。在应用程序的所有控制器操作中,这是迄今为止最活跃的。由于它处理图像,因此每次页面加载都会触发 15-30 次控制器操作。我上面描述的行为暗示了一个可能的竞争条件。
标签: asp.net-mvc ninject