【问题标题】:Azure Stateful Service - with remoting and custom singleton serviceAzure 有状态服务 - 具有远程处理和自定义单例服务
【发布时间】:2023-09-29 07:44:02
【问题描述】:

我想在 .net 核心有状态服务中使用远程处理。我有一个需要作为单例添加的自定义类。这可能吗?

首先我尝试在 Startup.cs 的 ConfigureServices() 方法中注册自定义类,但后来我意识到这个方法永远不会被调用,因为我使用 return this.CreateServiceRemotingReplicaListeners(); 在 CreateServiceReplicaListeners() 方法中生成我的副本侦听器,并删除了Kestrel 配置(这将使该方法被调用)。

有没有办法让 Startup.cs 的 ConfigureServices() 方法被调用,或者在保持远程配置的同时将单例服务添加到另一个地方?

MyStefulService.cs 类中的 CreateServiceReplicaListeners() 方法如下所示:

protected override IEnumerable<ServiceReplicaListener>
CreateServiceReplicaListeners()
{
   return this.CreateServiceRemotingReplicaListeners();
}

Startup.cs 中的 ConfigureServices 方法如下所示:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IMyHandler>(x => new MyHandler());
    }

【问题讨论】:

    标签: c# remoting service-fabric-stateful


    【解决方案1】:

    最后我找到了解决问题的方法:我使用Autofac 来确保我注册的类在使用时都是同一个实例。 我用 Autofac 容器扩展了 Program.cs,所以我根本不需要 Startup.cs 类:

    我定义了我的自定义类的静态变量和一个 Autofac 容器,然后在 Main() 方法中我添加了实现:

    public static IContainer AutofacContainer;
    private static IMyHandler _handler;
    
    private static void Main()
    {
        try
        {
            if (_autofacContainer == null)
            {
                var builder = new ContainerBuilder();
    
                builder.RegisterType<MyHandler>()
                    .As<IMyHandler>()
                    .SingleInstance();
    
                _autofacContainer = builder.Build();
    
                _handler = autofacContainer.Resolve<IMyHandler>();
            }
    
            //[...] normal service registration continues here
        }
        catch (Exception e)
        {
            ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
            throw;
        }          
    }
    

    由于容器是静态和公共的,项目中的所有其他类都可以访问它并获取单例实例。 配置、环境变量等也可以从这里配置,类似于Startup.cs。

    【讨论】:

      最近更新 更多