我想这是可能的,但我不确定你是否想要这个。我会采取以下方法(未经测试,不确定它是否有效)。首先在您的解决方案中创建以下项目结构:
ServiceInterfaces
-
ServiceImplementations(参考ServiceInterfaces和ModelClasses)
ModelClasses
-
Host(参考ServiceInterfaces和ServiceImplementations)
-
Client(参考ServiceInterfaces和ModelClasses)
在ServiceInterfaces 中,您有一个这样的界面(我跳过了命名空间等以使示例更短):
[ServiceContract]
public interface IMyService<T>
{
T GetObject(int id);
}
在ServiceImplementations 中有一个实现IMyService<T> 的类:
public class MyService<T> : IMyService<T>
{
T GetObject(int id)
{
// Create something of type T and return it. Rather difficult
// since you only know the type at runtime.
}
}
在Host 中,您在App.config(或Web.config)文件中为您的服务提供了正确的配置,并使用以下代码来托管您的服务(假设它是一个独立的应用程序):
ServiceHost host = new ServiceHost(typeof(MessageManager.MessageManagerService))
host.Open();
最后在Client 中,您使用ChannelFactory<TChannel> 类来定义代理:
Binding binding = new BasicHttpBinding(); // For the example, could be another binding.
EndpointAddress address = new EndpointAddress("http://localhost:8000/......");
IMyService<string> myService =
ChannelFactory<IMyService<string>>.CreateChannel(binding, address);
string myObject = myService.GetObject(42);
同样,我不确定这是否有效。诀窍是在主机和客户端之间共享您的服务接口(@987654345@)和域模型对象(ModelClasses)。在我的示例中,我使用一个字符串从服务方法返回,但它可以是来自 ModelClasses 项目的任何数据协定类型。