ServiceContainer, IoC, and disposable objects

后端 未结 3 1158
囚心锁ツ
囚心锁ツ 2021-02-06 07:40

I have a question, and I\'m going to tag this subjective since that\'s what I think it evolves into, more of a discussion. I\'m hoping for some good ideas or some thoug

3条回答
  •  孤城傲影
    2021-02-06 08:18

    One option might be to go with a factory pattern, so that the objects created directly by the IoC container never need to be disposed themselves, eg

    IBinaryDataProviderFactory factory =
        ServiceContainer.Global.Resolve();
    using(IBinaryDataProvider provider = factory.CreateProvider())
    {
        ...
    }
    

    Downside is added complexity, but it does mean that the container never creates anything which the developer is supposed to dispose of - it is always explicit code which does this.

    If you really want to make it obvious, the factory method could be named something like CreateDisposableProvider().

提交回复
热议问题