【问题标题】:Services as properties in WCF service服务作为 WCF 服务中的属性
【发布时间】:2017-03-02 10:42:01
【问题描述】:

我有一个用于在数据库上执行 CRUD 操作的通用服务,理想情况下我希望将其公开为 WCF 服务,如下所示:

[ServiceContract]
public interface ICrudService<T> where T : class
{
    [OperationContract]
    T Add(T arg);

    // Read ...
    // Update ...
    // Delete ...
}

很遗憾,WCF 不支持泛型。

WCF Generic Class

WCF exposing generic type 'T'

所以我想创建一个 WCF 服务,将其他服务作为属性公开。像这样:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    FooService FooService { get; }

    [OperationContract]
    BarService BarService { get; }
}

public interface ICrudService<T> where T : class
{
    T Add(T arg);

    // Read ...
    // Update ...
    // Delete ...
}

public class FooService : ICrudService<Foo>
{
}

public class BarService : ICrudService<Bar>
{
}    

它不会让我将服务用作运营合同。还有其他方法可以实现吗?

【问题讨论】:

  • 这是我严重质疑使用服务价值的地方。为什么不能在进程中进行数据库调用?
  • 我想允许从客户端调用操作。我需要使用 UWP 应用作为客户端。

标签: c# .net wcf generics


【解决方案1】:

确实如此:不幸的是,WCF 不支持泛型。但是有一种方法可以创建Dictionary&lt;string, object&gt; 作为输入。我不确定这是否是您想要的,但我遇到了同样的问题,我可以通过这种方式解决。

[Serializable]
public class WebServiceInputGetDataParams : ISerializable
{
    public Dictionary<string, object> Entries
    {
        get { return entries; }
    }


    private Dictionary<string, object> entries;
    public WebServiceInputGetDataParams()
    {
        entries = new Dictionary<string, object>();
    }
    protected WebServiceInputGetDataParams(SerializationInfo info, StreamingContext context)
    {
        entries = new Dictionary<string, object>();
        foreach (var entry in info)
        {
            entries.Add(entry.Name, entry.Value);
        }
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        foreach (var entry in entries)
        {
            info.AddValue(entry.Key, entry.Value);
        }
    }
}

它是一个输入类。你可以创建一个这样的方法:

public void TestMethod(WebServiceInputGetDataParams input)
{
    //access the input through dictiobnary
    input.Entries
}

【讨论】:

  • 您熟悉 wcf 概念吗?你想发布整个代码吗?它只是一个输入类。你应该自己写剩下的。
  • 对不起,我没有意识到受保护的方法是构造函数重载
  • 不客气。它发生在我们所有人身上。不是吗?
猜你喜欢
  • 2023-03-26
  • 2013-07-09
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
相关资源
最近更新 更多