c# - Register one type with multiple interfaces with one part of a collection causes Ambiguous Lifestyles error in Simple Injector -
so have class, implementing 2 interfaces:
interface iperson { } interface iman { } class person : iperson, iman { } and following setup of container
container.options.defaultscopedlifestyle = new aspnetrequestlifestyle(); and want register person class follows:
container.register<iperson, person>(lifestyle.scoped); and want classes implementing iman interface registered collection follows:
var assembly = assembly.load(new assemblyname("my.namespace")); container.registercollection(typeof(iman), assembly); when calling container.verify() results in simpleinjector.diagnosticverificationexception:
-[ambiguous lifestyles] registration iman (transient) maps same implementation (person) registration iperson (asp.net request) does, registration maps different lifestyle. cause each registration resolve different instance.
how prevent exception?
(we using simpleinjector v.3.3.2)
you should upgrade simple injector v4 , add following registration:
container.register<person>(lifestyle.scoped); so in total, configuration should be:
container.register<person>(lifestyle.scoped); container.register<iperson, person>(lifestyle.scoped); var assembly = assembly.load(new assemblyname("my.namespace")); container.registercollection(typeof(iman), assembly); there few things @ play here:
- since v4.0, simple injector automatically reuses
registrationinstances whenever can. means although there registrationiperson,personlifestyle, there 1 instance ofpersonperscope, since simple injector reuse samesimpleinjector.registrationinstance in control on creation ofpersoninstances. registercollectiontry reuse explicit registrations types in list , reuse it, making possible override default lifestyle such collection registration gets (whichtransient). in other words, callregistercollection(typeof(iman), new[] { typeof(person) })(which callregistercollectionmaps to), try explicit registration ofperson. because ofregister<person>(lifestyle.scoped)call, find explicit registration, allows collection return scoped instance well, removes error.
Comments
Post a Comment