0

我是 WCF 的初学者。我正在尝试使设备驱动程序网络可访问。我现在的代码,简化:

A.cs

public class A {
    public int source;
}

驱动程序.cs

public class Driver {
    // some fields here
    A a;

    // singleton class
    private Driver() {
        a = null;
        // some more code
    }

    // static methods
    public static Driver OpenDevice(int n) {
        Driver d = null;
        // some code
        i = GetBoardNumber();
        // some native code to actually open driver ONLY IF it wasn't already opened!
        d = new Driver();
        return d;
    }
    public static int GetDeviceNumber() {
        // some native code get device number
        return someInt;
    }

    // some non static methods which use native code
    // example:
    public int ResetDevice(){
        // some code
        // call native i_ResetDevice() method
        return code;
    }
}

DLLImport.cs

public class DllImport {
    // some code to import method definitions from dll
    // example:
    [DllImport("MyDeviceDriverProvidedForWindows.dll")]
        public static extern int i_ResetDevice();
    // some more code
}

这个驱动程序对我来说很好用。在控制设备的示例中,我只是简单地添加了对这个驱动程序的引用,并使用驱动程序的方法来控制设备。

MyService d = Driver.OpenDevice(0);
d.ControlDevice();

我的工作是让这个驱动程序可以远程访问,我选择使用 WCF 来完成。

因为,我已经实现了,所以我提取了一个接口,并通过放置 OperationContracts 和适当的位置将其转换为有效的 WCF 服务合同。这个提取的接口没有 OpenDevice 和 GetDeviceNumber 方法,因为它们是静态的。


我遇到的问题是:

1) 打开 WSDL 文件告诉我在客户端中使用类似这样的代码:

MyServiceClient client = new MyServiceClient();
// access client operations
// close client
client.Close();

这是什么MyServiceRefernce.MyServiceClientMyServiceReference是我添加到客户端的服务引用的名称)?为什么它在服务器上调用 MyService 类的私有构造函数?

2)我怎样才能在客户端做这样的事情?

MyServiceReference.Driver d = MyServiceRefernce.Driver.OpenDevice(0);

我已经阅读过InstanceContextMode但不确定如何在我的情况下使用它。

我知道很难理解我在问什么,但我也很难解释!我希望我身边有一个非常了解 WCF 的人。


我使用的实际驱动程序源位于此文件的 Assembly 文件夹中。

4

2 回答 2

2

通常 WCF 没有会话,因此所有调用都是相互独立的。因此,您应该将 Driver 函数封装到可服务的方法中。因此,一种方法将为设备提供一个工作单元,该设备将在每次调用时打开 -> 工作 -> 关闭。

于 2012-12-03T10:04:17.770 回答
2

您不会通过使服务类成为单例来使 WCF 服务使用单个实例。您需要配置 WCF 服务,使其仅使用单个实例。您还可以创建基于会话的 WCF 服务。例如,请参见此。

于 2012-12-03T10:09:01.677 回答