3

我想使用 LightInject 的构造函数注入功能,但我想先弄清楚 IDisposables 的生命周期管理。

考虑以下:

示例 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 是否跟踪注入的依赖项并自行处理它们?

4

1 回答 1

2

LightInject will only track instances it creates if the service/dependency is registered with the PerScopeLifetime or the PerRequestLifetime. Take a look at the following example:

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");
    }
}
于 2015-04-04T08:37:46.427 回答