Skip to content

Prevent Torn lifestyle warning when registering separate collections #1023

@dotnetjunkie

Description

@dotnetjunkie

Code to reproduce:

using SimpleInjector;

var container = new Container();

container.Register<TypeA>();
container.Register<TypeB>();

container.RegisterConditional<IEnumerable<IChild>>(
    container.Collection.CreateRegistration<IChild>(typeof(Child1), typeof(Child2)),
    c => c.Consumer.ImplementationType == typeof(TypeA));

container.RegisterConditional<IEnumerable<IChild>>(
    container.Collection.CreateRegistration<IChild>(typeof(Child3), typeof(Child4)),
    c => c.Consumer.ImplementationType == typeof(TypeB));

container.Verify();

public record TypeA(IEnumerable<IChild> Children);
public record TypeB(IEnumerable<IChild> Children);
public interface IChild { }
public class Child1 : IChild { }
public class Child2 : IChild { }
public class Child3 : IChild { }
public class Child4 : IChild { }

When run, the program produces the following error:

SimpleInjector.DiagnosticVerificationException: 'The configuration is invalid. The following diagnostic warnings were reported:
-[Torn Lifestyle] The registration for IEnumerable maps to the same implementation and lifestyle as the registrations for IEnumerable and IEnumerable do. They all map to IEnumerable (Singleton). This will cause each registration to resolve to a different instance: each registration will have its own instance.
See the Error property for detailed information about the warnings. Please see https://simpleinjector.org/diagnostics how to fix problems and how to suppress individual warnings.'

Fix

Simple Injector should detect Registration instances created with Collection.CreateRegistration and ignore them by default.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions