了解Autofac寿命范围 [英] Understanding Autofac lifetime scopes
问题描述
从Autofac的文档中,我了解到它一直引用它创建的每个IDisposable实现程序.因此,它可能导致OutOfMemoryException.因此,建议的解决依赖关系的方法是使用ILifetimeScope.
From the documentation of Autofac, I understand that it keeps a reference to every IDisposable implementor that it creates. Therefore it can lead to OutOfMemoryException. So the suggested way to resolve dependencies is by using a ILifetimeScope.
假设IService实现IDisposable.
Assume IService implements IDisposable.
class MaintenanceTask {
private IService service;
public MaintenanceTask(ILifetimeScope lifetimeScope) {
service = lifetimeScope.Resolve<IService>();
}
//...do your work
}
但是这种方法的问题是它隐藏了依赖项.我必须查看代码以了解该类所依赖的内容.还有其他方法可以更明确地处理此问题吗?更具体地说,无需查看代码即可使依赖关系更加明显?还是我完全误会了?
But the problem with this approach is that it hides dependencies. I have to look at the code to see what that class depends on. Is there any other way to handle this in a more explicit way? More specifically, making dependencies more obvious without having to look at code? Or am I totally mistaken?
推荐答案
传递生存期范围就像传递容器本身一样.它类似于服务定位器(反)模式,并且具有您所描述的问题:
依赖性变得不明显.
Passing in a lifetime scope is like passing in the container itself. It resembles the Service locator (anti-) pattern and has exactly the problem you described:
Dependecies become non-obvious.
一件事要问自己:
您的记忆确实有问题吗?如果没有的话,我也不会打扰.
One thing to ask yourself:
Are you actually having problems with your memory? If not, I wouldn't bother.
另一个指针:
如果您有应在使用后立即处置的个别服务,请使用工厂来创建它们,并使您的类依赖于工厂而不是服务本身.
Another pointer:
If you have individual services that should be disposed right after usage, use a factory to create them and make your class depend on the factory instead of the service itself.
生存期范围的使用方案有些不同:
当您需要本地合成根时使用它们.在Windows应用程序中,我从来不需要这样的东西,但是在Web应用程序中,会话"或请求"可能需要本地组合根.
The usage scenario for lifetime scopes is a little bit different:
They are used when you need a local composition root. I never had the need for something like this in a windows application, but in web applications a Session or Request can require a local composition root.
这篇关于了解Autofac寿命范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!