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

本文关键字:服务 客户端 接口 注入 简单 依赖 用于 | 更新日期: 2024-10-18 13:27:47

我目前正在ViewModel&直接调用服务公开的方法,例如:

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

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

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

public class ArticleViewModel : IServiceClient
{
    private IServiceClient ServiceClient { get; set; }
    public ArticleViewModel(IserviceClient serviceClient)
    {
       this.ServiceClient = serviceClient;
    }

我理解这将如何工作,但我正在努力编写接口:

Interface IMyServiceClient
{
   // ?
}

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

好吧,我是如何绕过这个的:

客户端中的服务引用提供了一个名为IServiceChannel的接口,该接口为您的服务定义了一个通道。我在运行时命中的第一个ViewModel中创建通道工厂。然后,该实例在整个应用程序中通过结果ViewModels的构造函数传递。我只是简单地将其传递到我的ViewModel构造函数中,如下所示:

 public ArticleDataGridViewModel(IMyServiceChannel myService)
    {
        this.MyService = myService;
        var factory = new ChannelFactory<IMyServiceChannel>("BasicHttpBinding_IMyService");
        MyService = factory.CreateChannel(); 

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

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

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

ViewModels准备要在视图中显示的数据,并实现表示逻辑(触发操作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不需要实现该接口。只需在构造函数中传递它,并将它保存到一个私有字段中。