如主题中的MSDN library所述'应用状态数据'我想存储数据并将其提供给所有用户。与在msdn示例中一样,我在Startup.cs文件中注册了名为MyShardData
的自定义服务:
public void ConfigureServices(IServiceCollection services)
{
[...]
services.AddSingleton<MyShardData>();
[...]
}
服务类非常简单:
public class MyShardData
{
public string Message { get; set; }
}
我想在两个请求之间共享消息:
[Route("[controller]")]
public class TestController : Controller
{
[HttpGet]
public IActionResult Index(MyShardData pMyShardData)
{
return Content(pMyShardData.Message);
}
[HttpPut]
public IActionResult SetMessage(MyShardData pMyShardData, string pMessage)
{
pMyShardData.Message = pMessage;
return NoContent();
}
}
在第一个请求中,我将消息&#39; Hello World&#39;并将值传递给服务的属性。在第二个请求中,我希望得到价值。问题:值为null:
方法&#39; AddSingleton&#39;让我想一想,MySharedData将被缓存在内存中,因为它是作为单例处理的。因为它是单例,我认为,我不需要将消息保存在静态属性中。这有什么不对?
答案 0 :(得分:1)
正如Frank Nielsen所说:在你的控制器构造函数中注入服务,如下所示:
private MyShardData _pMyShardData;
public TestController(MyShardData pMyShardData){
_pMyShardData = pMyShardData;
}
然后您可以使用私有字段设置并返回它:
[HttpGet]
public IActionResult Index()
{
return Content(_pMyShardData.Message);
}
[HttpPut]
public IActionResult SetMessage(string pMessage)
{
_pMyShardData.Message = pMessage;
return NoContent();
}
答案 1 :(得分:1)
您必须通过在控制器的构造函数中声明依赖项来注入您注册的服务。另外,请记住,您的单例不会阻止ASP.NET因空闲超时等原因而关闭。您最好使用外部第三方解决方案来保持状态(Redis,SQL Server等)。
[Route("[controller]")]
public class TestController : Controller
{
private readonly MyShardData _myShardData;
public TestController(MyShardData myShardData)
{
_myShardData = myShardData;
}
[HttpGet]
public IActionResult Index()
{
return Content(_myShardData.Message);
}
[HttpPut]
public IActionResult SetMessage(string pMessage)
{
_myShardData.Message = pMessage;
return NoContent();
}
}