Understanding Autofac lifetime scopes

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 20:06:41

问题


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.

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/13859671/understanding-autofac-lifetime-scopes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!