LightInject:构造函数注入和IDisposable

时间:2015-04-01 23:28:58

标签: c# dependency-injection light-inject

我想使用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吗?
  3. 修改 那么第二个问题是愚蠢的我意识到,PerContainerLifeTime实例当然是在容器处理时处理掉的。 我的整体问题是,LightInject跟踪注入的依赖关系,并自行处理它们吗?

1 个答案:

答案 0 :(得分: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");
    }
}