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 registration instances whenever can. means although there registration iperson , person lifestyle, there 1 instance of person per scope, since simple injector reuse same simpleinjector.registration instance in control on creation of person instances.
  • registercollection try reuse explicit registrations types in list , reuse it, making possible override default lifestyle such collection registration gets (which transient). in other words, call registercollection(typeof(iman), new[] { typeof(person) }) (which call registercollection maps to), try explicit registration of person. because of register<person>(lifestyle.scoped) call, find explicit registration, allows collection return scoped instance well, removes error.

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -