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

时间:2015-03-06 15:03:32

标签: c# wpf wcf mvvm dependency-injection

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

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

这导致ViewModel& amp; 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中找到绑定详细信息。

1 个答案:

答案 0 :(得分:1)

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

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

话虽这么说,你所要做的就是将你的服务传递给你的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不需要实现该接口。只需在构造函数中传递它并将其保存到私有字段中。