Autofac: How to limit the lifetime of an IDisposable object without passing around the IoC container

后端 未结 3 1374
無奈伤痛
無奈伤痛 2021-02-08 10:27

I\'m currently learning how to use Autofac, and I\'m stuck with disposing IDisposable objects deterministically. Let me first present the situation before I\'ll sta

3条回答
  •  别那么骄傲
    2021-02-08 11:04

    If you sometimes want to manage the lifetime of Apple instances yourself, and sometimes let the container handle it, then you can define two interfaces:

    public IApple
    {
       void Consume();
    }
    
    public IDisposableApple : IApple, IDisposable
    {
    }
    

    And then register the class twice:

    builder.RegisterType().As();
    builder.RegisterType().As().ExternallyOwned(); 
    

    You can then inject a DisposableAppleFactory into classes that need to create and dispose apples.

    For classes which just need an apple with the same lifetime as the container, you inject IApple instead.

    However, the fact that you need both may indicate that you are mixing newables and injectables. Apple may simply be a "newable" object, i.e. one that doesn't need to be managed by the IoC container.

提交回复
热议问题