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

后端 未结 3 1365
無奈伤痛
無奈伤痛 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 10:57

    The other answers here are insightful, but have a problem. In both cases, if Apple has other dependencies that need disposal, correct cleanup won't happen.

    Autofac 2 provides a new feature to help here, called "owned instances". I noticed that your registration code is Autofac 1.4, so if you're unable to upgrade let me know (there are other, less transparent, ways to do this.)

    Register Apple as usual (not externally owned):

    builder.RegisterType().As();
    

    Declare AppleFactory as:

    public delegate Owned AppleFactory();
    

    In Autofac 2, you do not need to call RegisterGeneratedFactory() anymore - this is automatic.

    Then, in HorseKeeper, feed the horse like this:

    public void FeedHorse()
    {
        using (var apple = appleFactory())
        {
            horse.Eat(apple.Value);
        }
    }
    

    (Note the .Value property to get the underlying IApple.

    At the end of the using block the apple, plus all of its dependencies, will be cleaned up.

    Any other components that use IApple directly (as dependencies) will get the usual behaviour.

提交回复
热议问题