z4kn4fein / stashbox

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

Please disable Lifetime validation by default #83

Closed schuettecarsten closed 4 years ago

schuettecarsten commented 4 years ago

Please disable Lifetime validation by default and add a method to "activate" it, like WithLifetimeValidation(). Usually, all features of Stashbox are activated using a `With... method, so please do so for lifetime validation.

z4kn4fein commented 4 years ago

Hey, Usually, it's working that way, however now I think it should be enabled by default because it's an important validation feature that could reveal lifetime misconfigurations. I'm trying to move that way where these kind of options are turned on by default. Like the circular dependency tracking, it's always turned on now and no way to disable it. Actually, there was no sense about leaving it disabled because the only thing you got was a stackoverflow when something was messed up.

schuettecarsten commented 4 years ago

I agree that lifetime validation is a very useful feature.

But sometimes, lifetimes cannot be configured correctly. Here is a small sample code, I only write the constructors here and the lifetimes that are used during service registration:

[Singleton]
public ProductCache(ProductRepository repo)

[Scoped]
public ProductService(ProductRepository repo, ProductCache cache)

[Scoped]
public ProductRepository(DataContext context)

public DataContext(...)

In this case, it's correct that the ProductRepository is registered in Scoped scope, I want one repository per Scope. The ProductService is also in Scoped lifetime.

But the ProductCache is a singleton and registered in singleton scope. The cache class should get its own repository and data context instances. Even if the repository and the context are registered scoped and transient, they should inherit the Singleton scope here (imho).

As this is by design, lifetime validation will throw exceptions here. That's why I have to disable validation for my code.

z4kn4fein commented 4 years ago

Yep, I know that there are cases when this validation fails but it's expected because the lifetime configuration is built consciously that way, this is why I added the option to turn it off. However, you are right and leave it disabled by default in the core project and turn it on wherever it's needed (in some extensions) might be a better approach. Also, I have to rethink the configuration mechanism, because when an extension turns a feature on by default, there is no easy way to disable.