//
// 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.Extensibility;
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.Utility;
namespace Microsoft.SqlTools.Hosting
{
///
/// 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(IProtocolEndpoint 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(IProtocolEndpoint 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
{
get
{
return typeof(T);
}
}
protected async Task HandleRequestAsync(Func> handler, RequestContext requestContext, string requestType)
{
Logger.Write(TraceEventType.Verbose, requestType);
try
{
THandler result = await handler();
await requestContext.SendResult(result);
return result;
}
catch (Exception ex)
{
await requestContext.SendError(ex.ToString());
}
return default(THandler);
}
public abstract void InitializeService(IProtocolEndpoint serviceHost);
}
}