gpt4 book ai didi

c# - 自托管 ServiceStack 服务器中的全局变量

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:56 25 4
gpt4 key购买 nike

我需要在我的 servicestack 自托管服务器中有一些“全局”变量,比如这里的 myList:

    public partial class Main : Form
{
AppHost appHost;

public Main()
{
InitializeComponent();

appHost = new AppHost();
appHost.Init();
appHost.Start(ListeningOn);

appHost.Plugins.Add(new ProtoBufFormat());
appHost.ContentTypeFilters.Register(ServiceStack.Common.Web.ContentType.ProtoBuf, (reqCtx, res, stream) => ProtoBuf.Serializer.NonGeneric.Serialize(stream, res), ProtoBuf.Serializer.NonGeneric.Deserialize);
}

/// <summary>
/// Create your ServiceStack http listener application with a singleton AppHost.
/// </summary>
public class AppHost : AppHostHttpListenerBase
{
public int intAppHost;
/// <summary>
/// Initializes a new instance of your ServiceStack application, with the specified name and assembly containing the services.
/// </summary>
public AppHost() : base("CTServer HttpListener", typeof(MainService).Assembly) { }

/// <summary>
/// Configure the container with th e necessary routes for your ServiceStack application.
/// </summary>
/// <param name="container">The built-in IoC used with ServiceStack.</param>
public override void Configure(Funq.Container container)
{
Routes
.Add<ReqPing>("/ping");
}
}
}

public class MainService : Service
{
public RespPing Any(ReqPing request)
{
// Add a value to a global list here
myList.Add(myData);

RespPing response = new RespPing();
return response;
}
}

我应该在哪里定义 myList,如何从那个位置访问它?我怎样才能以线程安全的方式做到这一点?在这种情况下,功能是存储收到的某个值,并在另一个实例中检查该值是否已在列表中。这是在实例之间共享数据的合适方式吗,还是我应该采用另一条路径?

谢谢!马蒂亚

最佳答案

这与ServiceStack 没有任何关系|因为 ServiceStack 服务只是 C# 类,每次都会 Autowiring 您注册的依赖项。

所以正常的 C# 规则适用,如果它是全局的,你可以将它设为静态,但由于 ASP.NET 和 HttpListener 是多线程的,你需要保护对它的访问,例如:

public class MainService : Service
{
static List<MyData> myList = new List<MyData>();

public RespPing Any(ReqPing request)
{
// Add a value to a global list here
lock(myList) myList.Add(myData);

RespPing response = new RespPing();
return response;
}
}

另一种方法是注册一个单例依赖项,并让它自动连接到每次需要它的所有服务,例如:

正常依赖

public class GlobalState
{
List<MyData> myList = new List<MyData>();

public void AddData(MyData myData)
{
lock(myList) myList.Add(myData);
}
}

应用程序主机

public override void Configure(Funq.Container container)
{
//All Registrations and Instances are singleton by default in Funq
container.Register(new GlobalState());
}

服务

public class MainService : Service
{
public GlobalState GlobalState { get; set; }

public RespPing Any(ReqPing request)
{
// Add a value to a global list here
GlobalState.AddData(myData);

RespPing response = new RespPing();
return response;
}
}

关于c# - 自托管 ServiceStack 服务器中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16253831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com