如何将依赖类传递给扩展方法?

时间:2019-07-19 06:51:12

标签: c# events dependency-injection extension-methods

我需要连接到服务器并收集数据进行处理。下面是我的核心类,它负责遍历所有服务器并尝试将它们连接以进行处理。

public class CoreDataProcessingEngine : ICoreDataProcessingEngine 
{
     private readonly COMLib.ServerGateway _aServerGw;
     private COMLib.ServerErrorInfo _aServerErrorInfo;

     Public CoreDataProcessingEngine()
     {
          _aServerGw = new COMLib.ServerGateway();
          _aServerErrorInfo = new COMLib.ServerErrorInfo();
     }

     //When service starts, I am collecting all the server details from config and trying to connect ONE BY ONE.

     public async Task Start()
     {
           List<Server> servers = ConfigurationManager.GetSection("servers") as List<Server>;
           foreach (var serverdetails in servers)
           {
                var data = Task.Run(() => ConnectToServer(serverdetails ));
           }
     }
}

这是我的ConnectToServer方法

  private async void ConnectToGateway(ServerDetails serverdetails )
  {
        await _aServerGw.connectToServerByName(serverdetails.serveraddress); 
  }

我将connectToServerByName方法扩展如下,该方法在单独的静态类中。

 public static class ComLibraryExtensions
 {

   public static Task connectToServerByName(this ProxyGW @this, string serveraddress)
    {
        var tcs = new TaskCompletionSource<object>();
        Action onSuccess = null;
        Action<int> onFailed = null;
        onSuccess = () =>
        {
            @this.onConnectSucceeded -= HandleManager_OnConnectSucceeded;
            @this.onConnectFailed -= HandleManager_OnConnectFailed;
            tcs.TrySetResult(null);
        };
        onFailed = hr =>
        {
            @this.onConnectSucceeded -= HandleManager_OnConnectSucceeded;
            @this.onConnectFailed -= HandleManager_OnConnectFailed;
            tcs.TrySetException(Marshal.GetExceptionForHR(hr));
        };
        @this.onConnectSucceeded += HandleManager_OnConnectSucceeded;
        @this.onConnectFailed += HandleManager_OnConnectFailed;
        @this.connectToGatewayByNameEx(serveraddress);
        return tcs.Task;
    }

    private static void HandleManager_OnConnectFailed(int hr)
    {
         //How do I get access to dependent objects here?    
         //Like ILogger ??
         _logger.Information(hr);
    }

    private static void HandleManager_OnConnectSucceeded()
    {
         //How do I get access @this??              
         @this.enableNotifications(true);//fails , it says @this does not exists
    }
   }

问题是:

  1. _aServerGw事件中如何访问HandleManager_OnConnectSucceeded,因为我想基于success事件设置一些属性。
  2. 如何在扩展类(如ILogger)中访问依赖对象?

0 个答案:

没有答案