将WCF服务代理注入viewmodel

时间:2012-09-12 16:11:59

标签: wcf silverlight silverlight-4.0 dependency-injection prism-4

我目前使用Prism和MEF的Silverlight应用程序。我在此应用程序中连接到多个WCF服务,但使用“控制器”类来保存实例化的客户端生成的服务代理对象。

我想要做的是将服务引用注入此控制器(就像我目前使用IEventAggregator一样)。我不确定该怎么做。我是否需要创建一个实现服务契约接口的包装类,并保存对服务代理对象的引用?

我现在做的事情:

/// <summary>
/// WCF client used to communitcate with the data WCF service
/// </summary>
private DataClient _dataClient;  // DataClient is the client generated object from a service reference

/// <summary>
/// Region manager for the application
/// </summary>
private IRegionManager _manager;

/// <summary>
/// Application event aggregator
/// </summary>
private IEventAggregator _eventAggregator;

/// <summary>
/// Constructor. Initializes the statistics controller, hooks up all services, and initializes all commands.
/// </summary>
/// <param name="manager"></param>
[ImportingConstructor]
public ZOpportunityController(IRegionManager manager, IEventAggregator events)
{
    _manager = manager;
    _eventAggregator = events;

    //hookup a WCF service used to retrive GP data
    _dataClient = new ZellerGpDataClient();  
    _dataClient.OpenCompleted += new EventHandler<AsyncCompletedEventArgs>(_dataClient_openCompleted);
    _dataClient.GetCustomersCompleted += new EventHandler<GetCustomersCompletedEventArgs>(_dataClient_GetCustomersCompleted);
    _dataClient.OpenAsync();
}

正如你在这里看到的,我连接到我的控制器构造函数中的服务,但我想将服务对象注入控制器,就像我使用IRegionManager和IEventAggregator一样。

编辑: This blog post正是我想要实现的目标。

1 个答案:

答案 0 :(得分:2)

ClientBase<TChannel>派遣客户并使其实施您的服务合同。合同的实施看起来类似于:

public class MyClient : ClientBase<IMyService>, IMyService
{
  void IMyService.DoSomething(Foo bar)
  {
    this.Channel.DoSomething(bar);
  }
}

现在您可以使用MEF或任何其他容器注册该实现,并通过构造函数注入它。