C# ASP.NET内核如何在ServiceBuilder中传递参数
我从Michael McKenna的博客上读到了一篇非常有用的关于创建多租户应用程序的文章,但我有几个问题。 TenantMiddleware类中的第一个常量为Constants.HttpContextTenantKey未定义,这可能是由于缺少一些代码,我同时设置了一个常量字符串 主要问题是,当我在启动时调用服务时,我希望传递InMemoryTechntStore类中的租户数组。我已经修改了InMemoryTenantStore类C# ASP.NET内核如何在ServiceBuilder中传递参数,c#,asp.net-core,.net-core,dependency-injection,C#,Asp.net Core,.net Core,Dependency Injection,我从Michael McKenna的博客上读到了一篇非常有用的关于创建多租户应用程序的文章,但我有几个问题。 TenantMiddleware类中的第一个常量为Constants.HttpContextTenantKey未定义,这可能是由于缺少一些代码,我同时设置了一个常量字符串 主要问题是,当我在启动时调用服务时,我希望传递InMemoryTechntStore类中的租户数组。我已经修改了InMemoryTenantStore类 MemorytenantStore中的公共类:ITenantSt
MemorytenantStore中的公共类:ITenantStore
{
私人只读租户【】\u租户;
公共InMemoryTenantStore(租户[]租户)
{
_租户=租户;
}
但是我不知道如何在调用服务中传递数组。我想我需要调整这段代码
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;
}
public-TenantBuilder with-Store(ServiceLifetime=ServiceLifetime.Transient),其中V:class,ITenantStore
{
_Add(servicescriptor.descripe(typeof(ITenantStore)、typeof(V)、life));
归还这个;
}
但是我找不到任何关于这方面的例子,不幸的是,我无法访问作者的博客。要通过
ServiceDescriptor
创建对象实例,并使用参数,您必须向其提供实现工厂,而不仅仅是实现类型
您可以通过两种方式执行此操作:
之前使用store
方法创建实例TenantBuilder
创建实现工厂(使用lambda或单独的方法)//在外部创建实例
带有存储的public TenantBuilder(V存储,ServiceLifetime=ServiceLifetime.Transient),其中V:class,ITenantStore
{
_Add(servicescriptor.descripe(typeof(ITenantStore),provider=>store,life));
归还这个;
}
//实施工厂
带有存储的public TenantBuilder(Func implementationFactory,ServiceLifetime=ServiceLifetime.Transient),其中V:class,ITenantStore
{
_Add(servicescriptor.descripe(typeof(ITenantStore)、implementationFactory、life));
归还这个;
}
我就是这么做的
public class Constants
{
public static Dictionary<string, object> HttpContextTenantKey { get; private set; } = new Dictionary<string, object>();
}
公共类常量
{
公共静态字典HttpContextEntantKey{get;private set;}=new Dictionary();
}
感谢您的回答,我已按照第一个解决方案中的说明修改了TenantBuilder,并将Startup.cs中的代码更改为:`services.AddMultiTenancy().WithResolutionStrategy().WithStore(新的InMemoryTenantStore(租户));`我没有收到任何错误,但应用程序被冻结。@g.lorenzo我相信这不是由代码来回答的。你可以通过在调试时暂停应用程序来检查应用程序的执行路径,以查看应用程序冻结的位置。你是对的@picolino,应用程序冻结是因为另一个原因,我花了一段时间才发现调试是无用的。你的解决方案rks很有魅力,谢谢。关于“Constants.HttpContextEntantKey”未定义错误的任何更新?这如何解决问题?请提供更多上下文。这是为了解决上述博客中缺少/未定义的HttpContextEntantKey。
public class Constants
{
public static Dictionary<string, object> HttpContextTenantKey { get; private set; } = new Dictionary<string, object>();
}