LightInject:构造函数注入和IDisposable



我想使用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是否跟踪注入的依赖项,并自行处理它们?

LightInject将只跟踪其创建的实例,前提是服务/依赖项已在PerScopeLifetime或PerRequestLifetime中注册。看看下面的例子:

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");
    }
}

相关内容

  • 没有找到相关文章

最新更新