本文主要介绍在.NET Core中想要使用WCF进程通信的替代方案,使用IpcServiceFramework实现,它允许以WCF样式创建服务,.NET Core不支持WCF,因为它是Windows特定技术,而.NET Core应该是跨平台的。

1、IpcServiceFramework简介

.NET Core轻量级进程间通信框架,允许通过命名管道和/或TCP调用服务(与WCF类似,目前.NET Core不可用)。还支持通过SSL进行安全通信。

支持在服务契约中使用原始或复杂类型。

支持服务器端的多线程,具有可配置的线程数(仅限命名管道端点)。

ASP.NET核心依赖注入框架友好。

2、IpcServiceFramework使用示例代码

1)创建 service contract

public interface IComputingService
{
float AddFloat(float x, float y);
}

2)实现service

class ComputingService : IComputingService
{
public float AddFloat(float x, float y)
{
return x + y;
}
}

3)在控制台应用程序中托管service

class Program
{
    static void Main(string[] args)
    {
        // configure DI
        IServiceCollection services = ConfigureServices(new ServiceCollection());
        // build and run service host
        new IpcServiceHostBuilder(services.BuildServiceProvider())
            .AddNamedPipeEndpoint<IComputingService>(name: "endpoint1", pipeName: "pipeName")
            .AddTcpEndpoint<IComputingService>(name: "endpoint2", ipEndpoint: IPAddress.Loopback, port: 45684)
            .Build()
            .Run();
    }
    private static IServiceCollection ConfigureServices(IServiceCollection services)
    {
        return services
            .AddIpc()
            .AddNamedPipe(options =>
            {
                options.ThreadCount = 2;
            })
            .AddService<IComputingService, ComputingService>();
    }
}

4)从客户端进程调用service

IpcServiceClient<IComputingService> client = new IpcServiceClientBuilder<IComputingService>()
    .UseNamedPipe("pipeName") // or .UseTcp(IPAddress.Loopback, 45684) to invoke using TCP
    .Build();
float result = await client.InvokeAsync(x => x.AddFloat(1.23f, 4.56f));

IpcServiceFrameworkhttps://github.com/jacqueskang/IpcServiceFramework

推荐文档