You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何结合Generic Host与Autofac实现多租户?

在C# Generic Host中结合Autofac实现多租户的疑问

我尚未找到在C#中结合Generic Host使用多租户的解决方案(或示例)。

Autofac仓库中提供的控制台应用、MVC和WCF多租户示例所采用的策略,在我看来并不适用于Generic Host场景——因为Autofac需要访问IContainer实例才能创建多租户容器。

是否存在在Generic Host与Autofac结合的场景下使用多租户的方法?感谢!

我已阅读Autofac官方仓库中的相关示例并进行了一些实验,但未找到可行的解决方案。涉及的示例包括:

  • Generic Host基础示例
  • 控制台应用多租户示例
  • MVC应用多租户示例
  • WCF服务多租户示例

以下是我实验时使用的标准Generic Host示例代码,我添加了注释以突出当前遇到的问题:

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Multitenant;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace AutoFacMultiTenantExploration;

internal class Program
{
    static async Task Main(string[] args)
    {
        AutofacServiceProviderFactory factory = new();

        var host = Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(factory)
            .ConfigureServices(ConfigureServices)
            .ConfigureContainer<ContainerBuilder>(ConfigureContainer)
            .UseConsoleLifetime()
            .Build();

        // 需要IContainer实例才能在此处创建MultitenantContainer(_myTenantIdentificationStrategy...);

        await host.RunAsync();
    }

    private static void ConfigureServices(HostBuilderContext context, IServiceCollection collection)
    {
        // 需要IContainer实例才能在此处创建MultitenantContainer(_myTenantIdentificationStrategy...);

        collection.AddHostedService<HostedService>();
        collection.AddSingleton<MyTenantIdentificationStrategy>();
    }

    private static void ConfigureContainer(HostBuilderContext context, ContainerBuilder builder)
    {
        // 需要IContainer实例才能在此处创建MultitenantContainer(_myTenantIdentificationStrategy...);

        builder.RegisterType<Logger>().As<ILogger>();
    }
}

// Generic Host未注册IContainer,因此无法在此处通过IHostedService注入实例
internal class HostedService(ILogger logger) : IHostedService
{
    private readonly ILogger _logger = logger;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Starting hosted service");

        // 需要IContainer实例才能在此处创建MultitenantContainer(_myTenantIdentificationStrategy...);


        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Stopping hosted service");
        return Task.CompletedTask;
    }
}
internal class Logger : ILogger
{
    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
    {
        Console.Out.WriteLineAsync($"Logger: {formatter.Invoke(state, exception)}");
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        throw new NotImplementedException();
    }

    public IDisposable? BeginScope<TState>(TState state) where TState : notnull
    {
        throw new NotImplementedException();
    }
}

internal class MyTenantIdentificationStrategy : ITenantIdentificationStrategy
{
    public int Identity { get; set; } = 0;

    public bool TryIdentifyTenant(out object? tenantId)
    {
        tenantId = Identity;
        return true;
    }
}

内容的提问来源于stack exchange,提问作者Jan Johansson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 13:22:05