2014-04-14 36 views
3

我寫周圍autofac一個適配器,以及需要提供的實現:Autofac檢查類型的生命週期範圍正在解決

T ResolveSingleton<T>() 

哪裏,當且僅當類型與註冊此方法將返回一個實例單身一生,否則會拋出一個錯誤。

我是新來的autofac,想知道是否有一種方法來查詢一個類型的註冊生命週期的容器?

謝謝!

回答

3

望着Autofac源代碼,你就可以看到,SingleInstance執行是這樣的:

public IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> SingleInstance() 
    { 
     RegistrationData.Sharing = InstanceSharing.Shared; 
     RegistrationData.Lifetime = new RootScopeLifetime(); 
     return this; 
    } 

所以你必須檢查ComponentRegistry匹配這些品質註冊。

public T ResolveSingleton<T>() 
    { 
     IComponentRegistration reg; 
     if (_context.ComponentRegistry.TryGetRegistration(new TypedService(typeof (T)), out reg)) 
     { 
      if (reg.Lifetime is RootScopeLifetime && reg.Sharing == InstanceSharing.Shared) 
       return (T) _context.ResolveComponent(reg, Enumerable.Empty<Parameter>()); 
     } 

     throw new Exception(); 
    }