//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.Hosting.Utility;
namespace Microsoft.SqlTools.Hosting.Extensibility
{
///
/// Defines a hosted service that communicates with external processes via
/// messages passed over the . The service defines
/// a standard initialization method where it can hook up to the host.
///
public interface IHostedService
{
///
/// Callback to initialize this service
///
/// which supports registering
/// event handlers and other callbacks for messages passed to external callers
void InitializeService(IServiceHost serviceHost);
///
/// What is the service type that you wish to register?
///
Type ServiceType { get; }
}
///
/// Base class for implementations that handles defining the
/// being registered. This simplifies service registration. This also implements which
/// allows injection of the service provider for lookup of other services.
///
/// Extending classes should implement per below code example
///
/// [Export(typeof(IHostedService)]
/// MyService : HostedService<MyService>
/// {
/// public override void InitializeService(IServiceHost serviceHost)
/// {
/// serviceHost.SetRequestHandler(MyRequest.Type, HandleMyRequest);
/// }
/// }
///
///
/// Type to be registered for lookup in the service provider
public abstract class HostedService : IHostedService, IComposableService
{
protected IMultiServiceProvider ServiceProvider { get; private set; }
public virtual void SetServiceProvider(IMultiServiceProvider provider)
{
ServiceProvider = provider;
}
public Type ServiceType => typeof(T);
protected async Task HandleRequestAsync(
Func> handler,
RequestContext requestContext,
string requestType)
{
Logger.Write(TraceEventType.Verbose, requestType);
try
{
THandler result = await handler();
requestContext.SendResult(result);
return result;
}
catch (Exception ex)
{
requestContext.SendError(ex.ToString());
}
return default(THandler);
}
protected async Task HandleSyncRequestAsAsync(
Func handler,
RequestContext requestContext,
string requestType)
{
Logger.Write(TraceEventType.Verbose, requestType);
return await Task.Factory.StartNew(() => {
try
{
THandler result = handler();
requestContext.SendResult(result);
return result;
}
catch (Exception ex)
{
requestContext.SendError(ex.ToString());
}
return default(THandler);
});
}
public abstract void InitializeService(IServiceHost serviceHost);
}
}