C# 具有不同生命周期的Autofac注册模块取决于应用程序(控制台或web)

C# 具有不同生命周期的Autofac注册模块取决于应用程序(控制台或web),c#,autofac,C#,Autofac,我有一个classlib,用于控制台应用程序和Web API。我使用Autofac模块注册依赖项,如下所示: public class TenantAutofacModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())

我有一个classlib,用于控制台应用程序和Web API。我使用Autofac模块注册依赖项,如下所示:

public class TenantAutofacModule : Autofac.Module
  {
    protected override void Load(ContainerBuilder builder)
    {
      builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
        .Where(t => t.Name.EndsWith("Service"))
        .AsImplementedInterfaces()
        .InstancePerTenant();
    }
  }
上面的生命周期InstancePerTenant适用于Web API,而不适用于控制台应用,因为生命周期范围需要HTTP请求

在TenantautoFac模块中,我想知道是否有一种方法可以知道谁是调用方,以便我可以使用InstancePerTenant或InstancePerLifetimeScope注册生命周期

上面的生命周期InstancePerTenant适用于Web API,而不适用于控制台应用,因为生命周期范围需要HTTP请求

InstancePerTenant不需要HTTP请求。这取决于您的ITenantIdentificationsStrategy实施

配置容器时,可以根据配置选择不同的实现

if(config.useConsole) {
    builder.RegisterType<ConsoleTenantResolverStrategy>()
           .As<ITenantIdentificationStrategy>()
           .SingleInstance();
} else {
    builder.RegisterType<WebTenantResolverStrategy>()
           .As<ITenantIdentificationStrategy>()
           .SingleInstance();
}
要获得您自己的配置,您可以阅读它,它将为您提供.NETCore的指导