ServiceContainer, IoC, and disposable objects

后端 未结 3 1119
囚心锁ツ
囚心锁ツ 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条回答
  • You actually came up with a very dirty solution: your IService contract violates the SRP, wich is a big no-no.

    What I recommend is to distinguish so-called "singleton" services from so-called "prototype" services. Lifetime of "singleton" ones is managed by the container, which may query at runtime whether a particular instance implements IDisposable and invoke Dispose() on shutdown if so.

    Managing prototypes, on the other hand, is totally the responsibility of the calling code.

    0 讨论(0)
  • 2021-02-06 08:17

    (Disclaimer: I'm answering this based on java stuff. Although I program C# I haven't proxied anything in C# but I know it's possible. Sorry about the java terminology)

    You could let the IoC framework inspect the object being constructed to see if it supports IDisposable. If not, you could use a dynamic proxy to wrap the actual object that the IoC framework provides to the client code. This dynamic proxy could implement IDisposable, so that you'd always deliver a IDisposable to the client. As long as you're working with interfaces that should be fairly simple ?

    Then you'd just have the problem of communicating to the developer when the object is an IDisposable. I'm not really sure how this'd be done in a nice manner.

    0 讨论(0)
  • 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<IBinaryDataProviderFactory>();
    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().

    0 讨论(0)
提交回复
热议问题