我想使用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()
    {

    }
 }


我对两个示例的疑问:


Foo被处置后,将由IBar上的LightInject调用Dispose方法,还是应该自己处置?
如果IBar使用的是PerContainerLifeTime,则在处置每个Foo实例之后会调用Dispose吗?


编辑
好吧,我意识到第二个问题很愚蠢,当容器被处置时,PerContainerLifeTime实例当然也被处置。
我的总体问题是,LightInject是否跟踪注入的依赖项并自行处理?

最佳答案

如果服务/依赖项已在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");
    }
}

08-07 03:30