I'd like to use LightInject's constructor injection feature, but I'd like to clear up things first about lifetime management of IDisposables.
Consider the following:
Example A
public class Foo : IDisposable
{
readonly IBar bar;
public Foo(IBar bar)
{
this.bar = bar;
}
public void Dispose()
{
}
}
Example B
public class Foo : IDisposable
{
readonly IBar bar;
public Foo(Func<string, IBar> bar)
{
this.bar = bar("myParameter");
}
public void Dispose()
{
}
}
My questions for both examples:
Edit Well the 2nd question is stupid I realize, a PerContainerLifeTime instance is of course disposed when the container is Disposed. My overall question would be, is LightInject tracking injected dependencies, and dispose them itself?
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With