java - DI-container vs. Factories -


i know there many aricles , threads on dependency injection, not on depenedency-injection-containers. found this 1 fabien potencier quite helpful, although targets php. more read containers come conclusion such none more simple collection of factory-methods, true?

a deeper , more concrete view: when injecting dependency object

foo.bar = new dependency(); 

i write

foo.bar = new myfactory.createdependency(); 

or container

foo.bar = mycontainer.createdependency(); 

here container within last approach not have 1 many other methods create other types also, container factory-methods, right?

the whole point of di containers never need/should write code

foo.bar = mycontainer.createdependency(); 

it considered antipattern. di container should used once in composition root(it main di container usage pattern).

di container automatically construct objects , inject dependencies via constructors or properties based on configuration. in case of factory have yourself. beside creation di containers provide with:

lifetime management. every time dependency needed container might inject same object(singleton lifetime), or return new everytime.

limited aop capabilities such method call interception , executing custom logic before , after methods.

you might take book dependency injection in .net. helped me lot understand di containers, patterns of usage , dependency injection in general.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -