在 Mvc.Controller 中使用服务器 [英] Using Server in Mvc.Controller

查看:21
本文介绍了在 Mvc.Controller 中使用服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 Mvc.Controller 继承了自己的 App.Controller,然后我的所有控制器都继承自它.我使用接口编写了一个提供程序并将其实现为 MyService 并且构造函数采用 Mvc.ControllerServer 属性,它是 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.

但是,我在 App.Controller 的构造函数中实例化了 MyService.问题是在构造MyService时,Controller的Server属性为null.我已经使用 public Controller () : base() { } 来获取要构建的基础.但是,Server 仍然是 null.

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 的建议,当我的应用程序在属性 get 方法中构造 MyService 时,Server 仍然为空.

Well, I have implemented tvanfosson's suggestion, and when my app constructs MyService in the property get method, Server is still null.

编辑 2: 没关系,我是个傻瓜.我还有另一个 Controller 使用 Server 并且没有改变它.案件已结.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆