Lea*_*ner 7 c# service wcf contracts
我有一个关于WCF大师的新问题.
所以,我有一个类User,它接近我用于数据库操作的DB的'User'表示.现在,我想有两个不同的服务合同,使用这个类作为数据合同,但每个都以他们自己的方式......我的意思是,
public class DBLayer
{
void InsertUsers(List<User> userList)
{
// both 'PropertyVisibleForService1' and 'PropertyVisibleForService2'
// are used HERE to be inserted into their columns
}
}
[DataContract]
public class User
{
[DataMember] public string PropertyVisibleOnlyForService1{...}
[DataMember] public string PropertyVisibleOnlyForService2{...}
}
[ServiceContract]
public interface IService1
{
List<User> GetUsers(); // user with 'PropertyVisibleOnlyForService1' inside
}
[ServiceContract]
public interface IService2
{
List<User> GetUsers(); // user with 'PropertyVisibleOnlyForService2' inside
}
Run Code Online (Sandbox Code Playgroud)
因此,我们的想法是每个服务都会得到一个不同类型的用户,即子集'User'.请记住,我想使用'User'原样进行数据库操作,我可以选择实现这一目标吗?我真的需要创建不同的数据合同还是有另一种更聪明的方法?
最好不仅要给我解决方案,还要向我解释一些最佳实践和替代方案.
先感谢您.
EDIT1:我在这里添加了一个虚拟DBLayer类,以便更好地概述,以及为什么我认为在这种情况下继承可能不太好.
一个解决方案是将另一个' UserForService1'和' UserForService2'作为数据合同,从最终映射到/'到' User',但我想要一些其他的观点.
EDIT2:在这种情况下帮助我的非常好的文章:http://bloggingabout.net/blogs/vagif/archive/2009/03/29/iextensibledataobject-is-not-only-for-backward-compatibility.aspx
您可以为每个服务创建单独的 DTO,但您的情况实际上非常适合装饰器模式:
[DataContract]
public class UserForService1 : User
{
private User mUser;
public UserForService1(User u)
{
mUser = u;
}
//expose only properties you'd like the user of this data contract to see
[DataMember]
public string SomeProperty
{
get
{
//always call into the 'wrapped' object
return mUser.SomeProperty;
}
set
{
mUser.SomeProperty = value;
}
}
// etc...
}
Run Code Online (Sandbox Code Playgroud)
对于 Service2 类似的代码,它只公开您关心的内容......
| 归档时间: |
|
| 查看次数: |
2899 次 |
| 最近记录: |