在Mvc.Controller使用服务器 [英] Using Server in Mvc.Controller
问题描述
我从 Mvc.Controller
我自己继承了 App.Controller
然后我所有的控制器继承。我写了使用接口的提供者和执行为为MyService
和构造函数的服务器
的属性 Mvc.Controller
是的HttpServerUtilityBase
。
I have my own inherited App.Controller
from Mvc.Controller
which then all of my controllers inherit from. I wrote a provider utilizing an interface and implemented it as MyService
and the constructor takes the Server
property of Mvc.Controller
which is of HttpServerUtilityBase
.
不过,我实例为MyService
在 App.Controller
的构造。问题是,控制器的服务器
属性是施工时空
为MyService
。我已经使用公共控制器():基地(){}
去建造基地。然而,服务器
遗体空
。
However, I instantiate MyService
in App.Controller
's constructor. The problem is that the Server
property of the Controller is null
when constructing MyService
. I have used public Controller () : base() { }
to get the base to be constructed. However, Server
remains null
.
我想避免 Web.HttpContext.Current.Server
如果可能的话。
I would like to avoid Web.HttpContext.Current.Server
if possible.
有没有人有这个问题的一个变通?
Has any one have a work around for this problem?
编辑:好了,我已经实现tvanfosson的建议,当我的应用程序构建为MyService
在属性 GET
方法服务器
仍是空。
Well, I have implemented tvanfosson's suggestion, and when my app constructs MyService
in the property get
method, Server
is still null.
编辑2:没关系,我是个混日子。我不得不使用其他控制器
服务器
藏汉并没有改变。结案。
Edit 2: Nevermind, I was a goof. I had another Controller
using Server
aswell and did not change that. Case closed.
推荐答案
使用延迟初始化来构建你的服务。
Use delayed initialization to construct your service.
private MyService service;
public MyService Service
{
get
{
if (this.service == null)
{
this.service = new MyService(this.Server);
}
return this.service;
}
}
那么,你的服务没有实际实例化,直到它在控制器的行动,并通过当时的服务器属性已设置时使用。
Then, your service isn't actually instantiated until it is used in the controller action and by that time the Server property has been set.
这篇关于在Mvc.Controller使用服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!