MultiTenant自定义ILogger - 不能从单例中使用作用域服务

时间:2017-11-23 09:42:26

标签: c# asp.net-core asp.net-core-mvc saaskit

我正在尝试为asp.net核心完成的每个日志添加租户名称。 我使用Sasskit进行多租户。

我得到一些范围问题。我希望得到一些关于如何让它发挥作用的反馈:

这是我的自定义记录器:

public class MultiTenantLogger : IMultiTenantProvider
{
    private AppTenant _tenant;

    public MultiTenantLogger(AppTenant tenant)
    {
        _tenant = tenant;
    }

    public string GetTenantName<T>()
    {
        var typeDisplayName = GetTypeDisplayName(typeof(T));

        if (_tenant == null)
        {
            return typeDisplayName;
        }

        return $"Tenant: {_tenant.Name}";
    }

}

public class MultiTenantLogger<T> : ILogger<T>
{
    private readonly ILogger _logger;

    public MultiTenantLogger(ILoggerFactory factory, IMultiTenantProvider multiTenantProvider)
    {
        if (factory == null)
        {
            throw new ArgumentNullException(nameof(factory));
        }
        if (multiTenantProvider == null)
        {
            throw new ArgumentNullException(nameof(multiTenantProvider));
        }

        var category = multiTenantProvider.GetTenantName<T>();
        _logger = factory.CreateLogger(category);
    }

    IDisposable ILogger.BeginScope<TState>(TState state) => _logger.BeginScope(state);

    bool ILogger.IsEnabled(LogLevel logLevel) => _logger.IsEnabled(logLevel);

    void ILogger.Log<TState>(LogLevel logLevel,
                             EventId eventId,
                             TState state,
                             Exception exception,
                             Func<TState, Exception, string> formatter)
        => _logger.Log(logLevel, eventId, state, exception, formatter);
 }

这是我的创业公司:

public void ConfigureServices(IServiceCollection services)
{
    _services = services;
    services.AddMultitenancy<AppTenant, CachingAppTenantResolver>();

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    // Add application services.
    services.AddTransient<IEmailSender, EmailSender>();

    services.Configure<MultitenancyOptions>(Configuration.GetSection("Multitenancy"));

    services.AddMvc();

    services.AddTransient<IMultiTenantProvider, MultiTenantLogger>();
    services.Replace(ServiceDescriptor.Transient(typeof(ILogger<>), typeof(MultiTenantLogger<>)));
}

我收到此错误:

  

无法使用作用域服务'AspNetMvcSampleModels.AppTenant'   来自singleton'Microsoft.AspNetCore.Hosting.IApplicationLifetime'。

欢迎任何有关如何使其正常工作的反馈!

1 个答案:

答案 0 :(得分:0)

我认为你需要同时制作Singleton或Scoped

您可以尝试替换

services.AddTransient<IMultiTenantProvider, MultiTenantLogger>();

services.AddSingleton<IMultiTenantProvider, MultiTenantLogger>();