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

后端 未结 3 1369
無奈伤痛
無奈伤痛 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:02

    The only way is to modify the Apple registration with the ExternallyOwned modifier. This instructs Autofac to not track the object for disposal, but rather let someone external (your code) handle the disposal. But as you state, you will now have to make sure that all instances of Apple are disposed manually, since you will get no automatic help from Autofac.

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

    With this registration your Feed code will work as expected, though.

    Note: on the discussion whether the interface should inherit IDisposable or not: IMO, when an interface inherits IDisposable, this is an indication to the "consuming" developer that the instance should be disposed at some point in time. In the case of IApple, since that interface is also IDisposable, the developer should make sure to dispose instances (and must also then be registered as ExternallyOwned). On the other hand, if the Apple class looked like this:

    class Apple: IApple, IDisposable
    { }
    

    consumers of the IApple is now fully unaware of the fact that instances is IDisposable. In this case we'll let the container handle disposal.

    So my conclusion is that it is up to me as the developer of Apple and IApple to choose whether I'll require consumers to handle disposal or leave it up to a container.

提交回复
热议问题