Conditionally register collections of non-generic abstractions in Simple Injector

1 week ago 7
ARTICLE AD BOX
using SimpleInjector; var container = new Container(); container.Register<TypeA>(); container.Register<TypeB>(); var typeAChildren = new List<IChild>() { new Child { Name = "ChildA1" }, new Child { Name = "ChildA2" } }; var typeBChildren = new List<IChild>() { new Child { Name = "ChildB1" }, new Child { Name = "ChildB2" } }; container.RegisterConditional<IEnumerable<IChild>>( Lifestyle.Singleton.CreateRegistration<IEnumerable<IChild>>(() => typeAChildren, container), c => c.Consumer.Target.Member.DeclaringType == typeof(TypeA)); container.RegisterConditional<IEnumerable<IChild>>( Lifestyle.Singleton.CreateRegistration<IEnumerable<IChild>>(() => typeBChildren, container), c => c.Consumer.Target.Member.DeclaringType == typeof(TypeB));

Shawn Miller's user avatar

using SimpleInjector; using SimpleInjector.Diagnostics; var container = new Container(); container.Register<TypeA>(); container.Register<TypeB>(); Registration regA = container.Collection.CreateRegistration<IChild>( typeof(Child1), typeof(Child2)); regA.SuppressDiagnosticWarning(DiagnosticType.TornLifestyle, "Not torn"); container.RegisterConditional<IEnumerable<IChild>>( regA, c => c.Consumer.ImplementationType == typeof(TypeA)); Registration regB = container.Collection.CreateRegistration<IChild>( typeof(Child3), typeof(Child4)); regB.SuppressDiagnosticWarning(DiagnosticType.TornLifestyle, "Not torn"); container.RegisterConditional<IEnumerable<IChild>>( regB, c => c.Consumer.ImplementationType == typeof(TypeB));

The calls to SuppressDiagnosticWarning are an unfortunate consequence of Simple Injector's diagnostic sub system. As it sees two registrations for the same implementation which it thinks leads to a Torn Lifestyle. However, the warning is a false positive as these are two completely different registrations. The calls to SuppressDiagnosticWarning, therefore, suppress this. We might fix this in the next minor release.

Steven's user avatar

1 Comment

...only var should be const here.

2026-01-22T18:31:54.483Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article