简单依赖注入的服务客户端接口?

Service Client Interface for Simple Dependency Injection?

我目前正在我的 ViewModel 中新建一个 WCF ServiceClient 实例,并直接调用该服务公开的方法,例如:

private string LoadArticle(string userName)
{
   MyServiceClient msc = new MyServiceClient();
   return msc.GetArticle(userName);
}

这导致 ViewModel 紧密耦合,Service.I 想使用构造函数依赖注入,传入 IMyServiceClient 接口,从而允许我对 ViewModel 进行单元测试。

我打算在我的 ViewModel 中实现接口:

public class ArticleViewModel : IServiceClient
{
    private IServiceClient ServiceClient { get; set; }

    public ArticleViewModel(IserviceClient serviceClient)
    {
       this.ServiceClient = serviceClient;
    }

我知道这将如何工作,但我正在努力实际编写界面:

Interface IMyServiceClient
{
   // ?
}

找不到这样的例子,可能是谷歌搜索不正确。

好的,这是我如何解决这个问题的:

客户端中的服务引用提供了一个名为 IServiceChannel 的接口,它为您的服务定义了一个通道。我在 运行 时间点击的第一个 ViewModel 中创建了通道工厂。然后,此实例在整个应用程序中通过后续 ViewModel 的构造函数传递。我只是像这样将其传递到我的 ViewModel 构造函数中:

 public ArticleDataGridViewModel(IMyServiceChannel myService)
    {
        this.MyService = myService;

        var factory = new ChannelFactory<IMyServiceChannel>("BasicHttpBinding_IMyService");
        MyService = factory.CreateChannel(); 

可以在 app.config 中找到绑定详细信息。

您的 ViewModel 不是服务,因此它也不应该实现 IServiceClient

ViewModels准备要在View中显示的数据并实现呈现逻辑(触发Action A时会发生什么?更新字段A,更改字段B的值等。当A为空时是否启用文本字段C?) .

也就是说,您所要做的就是将您的服务传递到您的 ViewModel 并调用它的方法。

public class ArticleViewModel : ViewModelBase 
{
    private IServiceClient serviceClient;
    public ArticleViewModel(IServiceClient client) 
    {
        this.serviceClient = client;
    }

    private string LoadArticle(string userName) 
    {
        return this.serviceClient.GetArticle(userName);
    }
}

您的 ViewModel 不需要实现该接口。只需将其传递给构造函数并将其保存到私有字段中即可。