z4kn4fein / stashbox

A lightweight, fast, and portable dependency injection framework for .NET-based solutions.

Home Page:https://z4kn4fein.github.io/stashbox

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Factory delegate registration and lifetime scopes

schuettecarsten opened this issue · comments

I use a factory delegate registration to create my dependencies in an "isolated scope". Unfortunately, the instances that are returned by the factory delegates, are registered in the calling scope when the services are activated. That might be fine in most cases, but I need to tell the service registration that these services are managed externally and should never be tracked/disposed by Stashbox. Is that possible?

Ok, that was simple.... had to use Transient lifetime, that's all ✅

Hey,
Thanks for reaching out! Yeah, transient lifetime could be a solution, but there's also a registration option for this that disables the tracking of created instances:

container.Register<A, B>(options => options.WithFactory(...).WithoutDisposalTracking());

This might be a better solution if you'd want to enable the tracking of transients in the future.
Hope this helps, let me know if you have further issues!

Okay, I just figured out that my problem is not solved.

I have a service A with lifetime Scoped. This service uses an instance of type B, which is Transient. I registered a factory for B, that uses "new" directly. I the scope for A is disposed, also B is disposed. How to prevent this? I want to let Stashbox know to always call the factory for B, but never dispose B.

And again.... WithoutDisposalTracking does the trick. ;-)