simpleinjector / SimpleInjector

An easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.
https://simpleinjector.org
MIT License
1.22k stars 152 forks source link

Improve diagnostic message when depending on mutable collection types #1003

Closed dotnetjunkie closed 3 months ago

dotnetjunkie commented 3 months ago

Considering the following repro:

var container = new Container();
container.Register<Foo>(Lifestyle.Singleton);
container.Collection.Register<IBar>(Type.EmptyTypes);
container.Verify();

public interface IBar { }
public class Foo(IBar[] bars);

This produces the following error message:

-[Lifestyle Mismatch] Foo (Singleton) depends on IBar[] (Transient).

The problem here is that the error message is very vague and doesn't explain why IBar[] is created as a transient dependency. See also this recent question.

Instead, we should consider the following extended error message:

-[Lifestyle Mismatch] Foo (Singleton) depends on IBar[] (Transient). IBar[] is a mutable collection type. Simple Injector always creates the mutable collection types array and List as transient, because a consumer can change the contents of such collection, which could break seemingly unrelated parts parts of your application if the collection was shared between consumers. Instead, either consider lowering the lifestyle of Foo or change Foo's dependency from IBar[] to one of the collection types that stream services (e.g. IEnumerable, ICollection, etc).