LightInject:构造函数注入和IDisposable
我想使用LightInject的构造函数注入功能,但我想先清理一下IDisposables的生命周期管理。LightInject:构造函数注入和IDisposable
考虑以下几点:
实施例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方法还是应该调用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");
}
}
谢谢你的答案:)所以,这将意味着一个PerScope实例配置范围配置时,和一个PerRequest实例在不再被引用时处置? (内部使用WeakReference?) – uzul 2015-04-04 16:24:05
不,这意味着PerRequest实例在范围结束时或处理范围处理完全相同时被处置:) – seesharper 2015-04-07 07:04:01
如果我不使用范围,是否意味着将会有内存泄漏使用PerRequest?如果是这样,我将不得不使用范围。 (特别是异步版本)。此外,我觉得需要一个“CacheLifeTime”,它会在超时之前返回相同的实例。有没有什么实现类似的东西? – uzul 2015-04-10 12:34:46
使用Autofac .... – nathanchere 2015-04-10 10:52:44