我习惯于使用类库(.Net Framework)创建.Net Framework控制台应用程序,并通过WCF服务从头开始公开Add(int x, int y)函数.然后,我使用控制台应用程序在服务器内代理调用此函数.

但是,如果我使用控制台应用程序(.Net Core)和类库(.Net Core),系统就会崩溃.ServiceModel不可用.我在谷歌上搜索了一下,但我还没有弄清楚在这个例子中是什么"取代"了WCF.

如何将类库中的Add(int x, int y)函数公开给控制台应用程序.净核心?我明白了.服务模型.由于这是一个跨平台的服务,我需要创建一个RESTful服务吗?

推荐答案

.NET Core不支持WCF,因为它是Windows特定的技术,而.NET Core应该是跨平台的.

如果您正在执行进程间通信,请考虑try IpcServiceFramework项目.

它允许创建WCF风格的服务,如下所示:

  1. Create service contract

    public interface IComputingService
    {
        float AddFloat(float x, float y);
    }
    
  2. Implement the service

    class ComputingService : IComputingService
    {
        public float AddFloat(float x, float y)
        {
            return x + y;
        }
    }
    
  3. Host the service in Console application

    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. Invoke the service from client process

.net相关问答推荐

在本地运行 Azure 函数会在 .NET7 升级后出现无运行时错误

类似于字典但没有值的 C# 数据 struct

单线程单元 - 无法实例化 ActiveX 控件

调整小数精度,.net

maxRequestLength 的最大值?

LINQ:确定两个序列是否包含完全相同的元素

我应该默认推荐密封类吗?

如何在 WPF 应用程序中使用 App.config 文件?

序列化私有成员数据

控制台应用程序的退出时

将跟踪输出重定向到控制台

为什么 LINQ .Where(predicate).First() 比 .First(predicate) 快?

HashSet 是否保留插入顺序?

String.Split 仅在 C# 中的第一个分隔符上?

如何将枚举值序列化为 int?

在未安装 Visual Studio 的机器上使用 FUSLOGVW.EXE

为什么发布和调试模式下的代码行为不同?

在 .NET 中,null 的哈希码是否应该始终为零

对构造函数进行单元测试重要吗?

不签署 .NET 程序集有什么问题吗?