简体   繁体   中英

Use interfaces and classes from an assembly in both WCF service and client

I have a project that communicates with a WCF service to access data. Sometimes the server is local and then it uses sql stored procedures to query the database directly.

To explain, suppose I have the following method:

Asset GetAsset(int AssetID);

This method is either exposed by the WCF service or used locally when querying the database directly. The problem I have is that the Asset object for the exposed method of the WCF service is different to the local method. ie Exposed service method is:

WcfService.Asset GetAsset(int AssetID);

Direct DB query method is:

LocalNamespace.Asset GetAsset(int AssetID);

While I can, I don't want to make the Direct DB query method use the WcfService Asset object since I want to be able to remove the WcfService if need be. Ideally I want to bundle the common objects/interfaces in a separate assembly that I can use both locally and on the service.

Do I have any a choice though? Maybe I don't know enough about the Referenced Assemblies option, although it is on.

You can definitely do that, it's one of the great strengths of WCF. Create a separate assembly containing your [DataContract] classes, [ServiceContract] interfaces, and nothing else. You can then use it however you like, in a WCF service, WCF client, or outside WCF altogether. Use the Referenced Assemblies option when adding a service reference to ensure that your contract assembly gets used.

You can go one better than that. Move your service contract implementation classes into another separate assembly. You can then call them directly in-process without going via a service call. This reduces your WCF service project to a collection of .svc files and a web.config .

在(添加服务引用)对话框中,按(高级...)按钮,然后选中(使用引用的程序集中的类型),这将解决问题,但是您应该将共享类放在单独的程序集中,并在两者中引用它客户和服务。

Create a Data Access Layer (DAL) object, perhaps in a seperate project all together.

Use this to handle all of your calls, instead of the accessing x assembly through reflection or by any other means, as you have mentioned add a reference to the object in both the WCF and your local project. You could use anything in this access layer, such as Entity Framework or NHibernate . Use the DAL object to call methods which go to the database.

Public Class ServiceDAL
{
  public Asset GetAsset(int id)
  {
    //Get your asset
    return asset;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM