z4kn4fein / stashbox

A lightweight, fast, and portable dependency injection framework for .NET-based solutions.
https://z4kn4fein.github.io/stashbox
MIT License
141 stars 10 forks source link

Factory delegate registration and lifetime scopes #96

Closed schuettecarsten closed 3 years ago

schuettecarsten commented 3 years ago

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?

schuettecarsten commented 3 years ago

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

z4kn4fein commented 3 years ago

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!

schuettecarsten commented 3 years ago

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.

schuettecarsten commented 3 years ago

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