Autofac:通过 IComponentRegistration 获取 ServiceLifetime

Autofac: Get ServiceLifetime by IComponentRegistration

通过Autofac.Core.IComponentRegistration获得Microsoft.Extensions.DependencyInjection.ServiceLifetime的正确方法是什么? 也就是说,这个方法如何实现?

private static Microsoft.Extensions.DependencyInjection.ServiceLifetime GetServiceLifetime(
    Autofac.Core.IComponentRegistration registration)
{
    ...
}

注意:我使用的是 Autofac 4.9.4 版本。

如果IComponentRegistration.Sharing属性是None,那么ServiceLifetime就是Transient

如果 属性 是 Shared,那么如果 Lifetime 属性 是 RootScopeLifetime 的实例(字面意思是 Lifetime is RootScopeLifetime) , 那么 ServiceLifetime 就是 Singleton.

ServiceLifetime.Scoped 值实际上是此处的 'else' 情况。

请注意,Microsoft DI 库没有 Instance per Matching Scopes 的概念,因此没有 100% 等价,但很接近。