c# - ContextDependent instance as Singleton in Simple Injector -
i have question regarding contextdependentextensions
of simpleinjector
library. have following extension add possibility adding elements injector context: contextdependentextensions
example:
var container = new container(); container.registerwithcontext(logger => new simplelogger("logger constructor parameter"));
here 1 interest line: should transient!
so, mean? , can use here lifestyle.singleton
or lifestyle.scoped
lifestyle?
can explain me? in advance.
with registerwithcontext
extension method, register predicate allows build instance using information consuming component. information supplied predicate extension method.
since means can built different instance per consuming type, making registration else transient, lead weird behavior. imagine instance registration of ilogger
abstraction create logger<t>
implementation t
type of consuming component:
container.registerwithcontext(c => (ilogger).container.getinstance( typeof(logger<>).makegenerictype(c.implementationtype)));
if make registration singleton, cause problems, if consuming components singleton, because same instance injected each consumer; while each consumer require own instance, because require own closed-generic version, namely: logger<consumer1>
, logger<consumer2>
, logger<consumer3>
, etc. instead, consumer same instance; instance created first resolved consumer. awful.
this same problem exist when using scoped instances; you'll same instance duration of scope, typically not want; instance should context dependent.
this serious limitation of registerwithcontext
extension method supplied simple injector v2 documentation. since limiting, simple injector v3 contains built-in registerconditional
method replaces registerwithcontext
extension method. v3 docs never refer registerwithcontext
anymore , advice use registerwithcontext
instead.
the documentation describes how use registerconditional
, shows following example:
container.registerconditional( typeof(ilogger), c => typeof(logger<>).makegenerictype(c.consumer.implementationtype), lifestyle.singleton, c => true);
since predicate of registration returns true
, registration isn't conditional, contextual.
using code can return logger<t>
specific consuming component, still ensure there @ 1 instance of each closed logger<t>
type; singleton.
the main difference between new registerconditional
, old registerwithcontext
can't supply factory delegate create instances. registerconditional
, simple injector in control on creation of instances (instead delegate) , allows creation of types incorporated in pipeline , allows simple injector verify , diagnose registered component , dependencies.
Comments
Post a Comment