2015-04-01 62 views
3

我想使用LightInject的構造函數注入功能,但我想先清理一下IDisposables的生命週期管理。LightInject:構造函數注入和IDisposable

考慮以下幾點:

實施例A

public class Foo : IDisposable 
{ 
    readonly IBar bar; 
    public Foo(IBar bar) 
    { 
     this.bar = bar; 
    } 

    public void Dispose() 
    { 

    } 
} 

實施例B

public class Foo : IDisposable 
{ 
    readonly IBar bar; 
    public Foo(Func<string, IBar> bar) 
    { 
     this.bar = bar("myParameter"); 
    } 

    public void Dispose() 
    { 

    } 
} 

我的問題對於這兩個例子:

  1. Foo處置後,IBar上的LightInject會調用Dispose方法還是應該調用dispose?
  2. 如果IBar正在使用PerContainerLifeTime,那麼在處理每個Foo實例後會調用Dispose嗎?

編輯 好第二個問題是愚蠢的我認識,一個PerContainerLifeTime實例是當容器被佈置佈置課程。 我的整體問題是,LightInject跟蹤注入的依賴關係,並將它們自己處置?

+0

使用Autofac .... – nathanchere 2015-04-10 10:52:44

回答

2

如果使用PerScopeLifetime或PerRequestLifetime註冊服務/依賴項,LightInject將僅跟蹤它創建的實例。 看看下面的例子:

class Program 
{ 
    private static IServiceContainer container = new ServiceContainer(); 

    static void Main(string[] args) 
    { 
     container.Register(f => new Foo("PerScopeFoo"), "PerScopeFoo", new PerScopeLifetime()); 
     container.Register(f => new Foo("PerRequestFoo"), "PerRequestFoo", new PerRequestLifeTime()); 
     container.Register(f => new Foo("PerContainerFoo"), "PerContainerFoo", new PerScopeLifetime()); 
     container.Register(f => new Foo("TransientFoo"), "TransientFoo"); 

     using (container.BeginScope()) 
     { 
      var first = container.GetInstance<Foo>("PerScopeFoo"); 
      var second = container.GetInstance<Foo>("PerScopeFoo"); 
      Debug.Assert(first == second); 

      first = container.GetInstance<Foo>("PerRequestFoo"); 
      second = container.GetInstance<Foo>("PerRequestFoo"); 

      Debug.Assert(first != second); 

      first = container.GetInstance<Foo>("PerContainerFoo"); 
      second = container.GetInstance<Foo>("PerContainerFoo"); 

      Debug.Assert(first == second); 

      first = container.GetInstance<Foo>("TransientFoo"); 
      second = container.GetInstance<Foo>("TransientFoo"); 

      Debug.Assert(first != second); 
     } 

     container.Dispose(); 

     Console.ReadKey(); 
    }   
} 

public class Foo : IDisposable 
{ 
    private readonly string name; 

    public Foo(string name) 
    { 
     this.name = name; 
    } 

    public void Dispose() 
    { 
     Console.WriteLine(name + " disposed"); 
    } 
} 
+0

謝謝你的答案:)所以,這將意味着一個PerScope實例配置範圍配置時,和一個PerRequest實例在不再被引用時處置? (內部使用WeakReference?) – uzul 2015-04-04 16:24:05

+0

不,這意味着PerRequest實例在範圍結束時或處理範圍處理完全相同時被處置:) – seesharper 2015-04-07 07:04:01

+0

如果我不使用範圍,是否意味着將會有內存泄漏使用PerRequest?如果是這樣,我將不得不使用範圍。 (特別是異步版本)。此外,我覺得需要一個「CacheLifeTime」,它會在超時之前返回相同的實例。有沒有什麼實現類似的東西? – uzul 2015-04-10 12:34:46