问题
I have a requirement to connect to the server and collect data for processing. Below is my core class, which is responsible for looping through all the servers and try connecting them for processing.
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 ));
}
}
}
Here is my ConnectToServer
method
private async void ConnectToGateway(ServerDetails serverdetails )
{
await _aServerGw.connectToServerByName(serverdetails.serveraddress);
}
I have extended the connectToServerByName
method as follow , which is in separate static class.
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
}
}
Question is:
- How do I get access to
_aServerGw
inHandleManager_OnConnectSucceeded
event, because I want to set some property based on thesuccess
event. - How do I get access to dependent objects here in extension classes like ILogger?
来源:https://stackoverflow.com/questions/57107015/how-do-i-pass-dependent-classes-to-extension-methods