使用 Ninject 解析 IContext?
我尝试在这段代码中使用 Ninject 解析 IContext 。我有一个 ContextProvider,它提供由 MySampleContext 继承的 DBContext。
protected virtual void Application_BeginRequest()
{
ContextProvider cp = new ContextProvider();
cp.SetCurrent(new MySampleContext());
}
或者我保持这种方式会更好吗..?问题是我无法访问内核,因为它是在引导程序中创建的。
有什么想法吗?我想要做的是使用 ninject 提供上下文,而不是实例化 mySampleContext
i try to resolve an IContext with Ninject in this code. I have a ContextProvider which provide the DBContext which is inherited by MySampleContext.
protected virtual void Application_BeginRequest()
{
ContextProvider cp = new ContextProvider();
cp.SetCurrent(new MySampleContext());
}
Or would it be better that i keep it this way.. ? The problem is that i can'T access Kernel since its created in a bootstrap.
Any idea ? What i want to do is provide a context using ninject instead of instancing mySampleContext
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将您的 Context 绑定在请求范围内,并在构造函数中将其注入您需要的地方。这样它只有在某个地方使用时才会被创建。
如果您确实需要在 ContextProvider 上设置它,则添加一个激活操作
Bind your Context in request scope and constructor inject it where ever you need it. This way it is only created when it is used somewhere.
In case you really need to set it on the ContextProvider then add an activation action
如果建议你的 2 个解决方案。如果您使用的是 ASP.NET MVC 3,您可能可以使用 DepencyResolver
或者您也可以在您的 MvcApplication (Global.asax) 中声明一个静态属性,例如
在您初始化内核的引导程序中
如果您遇到问题,因为您的内核不是尚未在 BeginRequest 中引导,我建议您处理以下事件而不是 BeginRequest
希望它有帮助。
If suggest your 2 solutions. If you are using ASP.NET MVC 3 you could probably use the DepencyResolver
Or you can also declare a static property in your MvcApplication (Global.asax) like
And in your bootstrapper where you init your Kernel
And if you get problems because your Kernel isn't bootstrapped yet in the BeginRequest, I suggest you to handle the following event instead of the BeginRequest
Hope it helps.
拥有 IDependencyResolver 支持 DI 并将应用程序与您正在使用的 IoC 分离的全部意义在于。如果您必须重构代码以使用不同的 IoC(例如 Structuremap),那么您的整个代码将不会依赖于 Ninject。
如果您处于无法使用构造函数注入的情况,则需要调用 System.Web.Mvc 中的静态 DependencyResolver,如下所示:
The entire point of having an IDependencyResolver support DI and decouple your applications from the IoC you are using. If you ever have to refactor your code to use a different IoC (Structuremap for example) you wont have dependencies on Ninject all through out your code.
If you are in the situation where you cannot use constructor injection, you need to call the static DependencyResolver in System.Web.Mvc like so: