繁体   English   中英

ASP.NET Core 如何在服务构建器中传递参数

[英]ASP.NET Core how to pass parameter in service builder

我已经阅读了 Michael McKenna 博客中关于创建多租户应用程序的非常有用的文章,但我有几个问题。 TenantMiddleware类中的第一个作为Constants.HttpContextTenantKey未定义,这可能是由于缺少一些代码,同时我设置了一个常量字符串。

主要问题是我想在启动时调用服务时在InMemoryTenantStore类中传递租户数组。 我修改了InMemoryTenantStore

 public class InMemoryTenantStore : ITenantStore<Tenant>
{
    private readonly Tenant[] _tenants;
    public InMemoryTenantStore(Tenant[] tenants)
    {
        _tenants = tenants;
    }

但我不知道如何在调用服务中传递数组。 我想我需要调整这段代码

 public TenantBuilder<T> WithStore<V>(ServiceLifetime lifetime = ServiceLifetime.Transient) where V : class, ITenantStore<T>
    {
        _services.Add(ServiceDescriptor.Describe(typeof(ITenantStore<T>), typeof(V), lifetime));
        return this;
    }

但是我找不到任何关于此的示例,不幸的是我无法访问作者博客。

要通过带有参数的ServiceDescriptor创建对象实例,您必须为其提供实现工厂,而不仅仅是实现类型。

您可以通过两种方式执行此操作:

  1. 只需在WithStore方法之前直接创建实例。
  2. 为构建TenantBuilder创建实现工厂(使用 lambda 或单独的方法)
// Creating instance outside
public TenantBuilder<T> WithStore<V>(V store, ServiceLifetime lifetime = ServiceLifetime.Transient) where V : class, ITenantStore<T>
{
    _services.Add(ServiceDescriptor.Describe(typeof(ITenantStore<T>), provider => store, lifetime));
    return this;
}

// Implementation factory
public TenantBuilder<T> WithStore<V>(Func<IServiceProvider, V> implementationFactory, ServiceLifetime lifetime = ServiceLifetime.Transient) where V : class, ITenantStore<T>
{
    _services.Add(ServiceDescriptor.Describe(typeof(ITenantStore<T>), implementationFactory, lifetime));
    return this;
}

这就是我所做的

public class Constants
    {
        public static Dictionary<string, object> HttpContextTenantKey { get; private set; } = new Dictionary<string, object>();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM