有没有办法从另一个项目中获取类的实例?

时间:2018-12-29 12:44:43

标签: c# .net

我有三个项目:
-客户端(Windows窗体)
-域(业务逻辑)
-服务(服务器)

Domain项目具有Service项目使用的AsyncServer和Client项目使用的AsyncClient。

我希望客户端获得与该服务实例相同的内容,因为我试图将Service添加为引用并将其设为静态并且不起作用,所以我还为其实现了Singleton Pattern,仍然不起作用,因为每次我尝试访问该服务时,它都会创建一个新实例。
那么有没有办法从Service项目中获取Program类的相同实例或另一个类?
谢谢!

服务项目的一部分代码:

聊天服务:

private static ChatService chatService;
private static readonly object syncObject = new object();

public AsyncServer AsyncServer { get; private set; }

private ChatService()
{
    InitializeComponent();

    AsyncServer = new AsyncServer();
}

public static ChatService GetInstance()
{
    lock (syncObject)
    {
        if (chatService == null)
        {
            chatService = new ChatService();
        }
    }

    return chatService;
}

程序:(使用console参数调用该服务)

public static ChatService ChatServer { get; private set; }

public static void Main(string[] args)
{
    if (args[0] == "console")
    {
        ChatServer = ChatService.GetInstance();
        ChatServer.RunAsConsole(args);
    }
    else
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            ChatService.GetInstance()
        };
        ServiceBase.Run(ServicesToRun);
    }
}

客户项目的一部分代码:
ChatForm:

private void OnConnectButtonClick(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txtIP.Text) && !string.IsNullOrEmpty(txtName.Text))
    {
        asyncClient = new AsyncClient(txtIP.Text);
        asyncClient.Connect();
        asyncServer = Service.Program.ChatServer.AsyncServer;
        asyncServer.ChatContentReceivedMethod += DisplayChatContent;
        SetControlsForConnection();
    }
}

如果我调试Client项目,则ChatServer为空。

0 个答案:

没有答案
相关问题