Is it “safe” to cache IServiceProvider for an app's lifetime?

后端 未结 2 1665
余生分开走
余生分开走 2021-01-16 09:08

I\'m using ASP.NET Core, and its builtin DI container. I\'m using a third-party library (NLog) which I can\'t change.

My Foo class has a dependency (by

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-16 09:30

    Addendum to @CodeCaster's excellent solution.

    It's important to change Func to Func>. Otherwise the container won't return new instances each time, even though you're using a delegate factory.

    Probably has something to do with the fact that a long-lived component (singleton) depends on a short-lived component (per-transaction). The Func<> prevents the captive dependency bug, but for the factory to also give you new instances each time, it needs to be Owned<>.

    I don't understand why, and it seems counter-intuitive, but that's how it works.

提交回复
热议问题