Injecting correct object graph using StructureMap in Queue of different Objects - dependency-injection

I have a queuing service that has to inject a different dependency graph depending on the type of object in the queue. I'm using Structure Map.
So, if the object in the queue is TypeA the concrete classes for TypeA are used and if it's TypeB, the concrete classes for TypeB are used.
I'd like to avoid code in the queue like:
if (typeA)
{
// setup TypeA graph
}
else if (typeB) {
// setup TypeB graph
}
Within the graph, I also have a generic classes such as an IReader(ISomething, ISpomethingElse) where IReader is generic but needs to inject the correct ISomething and ISomethingElse for the type. ISomething will also have dependencies and so on.
Currently I create a TypeA or TypeB object and inject a generic Processor class using StructureMap into it and then pass a factory manually inject a TypeA or TypeB factory into a method like:
Processor.Process(new TypeAFactory) // perhaps I should have an abstract factory...
However, because the factory then creates the generic IReader mentioned above, I end up manually injecting all the TypeA or TypeB classes fro there on.
I hope enough of this makes sense.
I am new to StructureMap and was hoping somebody could point me in the right direction here for a flexible and elegant solution.
Thanks

I don't know if I fully understand your question, but in general your queue processor needs access to some sort of factory for processing those objects. The most convenient approach would be if your queue consist of messages/commands (DTOs) and you have some sort of abstraction over command handling logic, such as ICommandHandler<TCommand>.
In that case your queue processor might look like this:
private readonly ICommandHandlerFactory factory;
public void Process(IEnumerable<object> commandQueue)
{
foreach (object command in commandQueue)
{
dynamic handler = this.factory.CreateHandlerFor(command.GetType());
handler.Handle((dynamic)command);
}
}

Related

Is there an easier alternative to Abstract Factory for sealed classes?

Based on this question, THE way to initialize new object with runtime parameters when using ioc-container is to create Abstract Factory.
In my example, I have this class:
internal sealed class AssetsDownloadingProcess
{
private readonly IBackgroundWorker _backgroundWorker;
private readonly IAssetsStorage _assetsStorage;
private readonly Parameters _parameters;
public AssetsDownloadingProcess(IBackgroundWorker backgroundWorker,
IAssetsStorage assetsStorage, Parameters parameters)
{
_parameters = parameters.Clone();
_backgroundWorker = backgroundWorker;
_assetsStorage = assetsStorage;
}
}
And a factory to construct it:
internal sealed class AssetsDownloadingProcessFactory
{
private readonly IBackgroundWorker _backgroundWorker;
private readonly IAssetsStorage _assetsStorage;
public AssetsDownloadingProcessFactory(IBackgroundWorker backgroundWorker,
IAssetsStorage assetsStorage)
{
_backgroundWorker = backgroundWorker;
_assetsStorage = assetsStorage;
}
public AssetsDownloadingProcess CreateProcess(
AssetsDownloadingProcess.Parameters parameters)
{
return new AssetsDownloadingProcess(
_backgroundWorker, _assetsStorage, parameters);
}
}
as you can see, AssetsDownloadingProcess does not implement any interface and will never be replaced with another class. Therefore this factory is nothing more than useless piece of code. It could be completely omitted in favour of AssetsDownloadingProcessFactory constructor. However, then I can't use dependency injection to constructor.
I would like to use benefits of Injection from my IoC Container without the hassle of creating factory and creating useless code. What is the correct way to do this? Am I missing something or using DI wrong?
In general, you should prevent using runtime data to create and initialize your application components, as described here. The mere fact that runtime data is passed in through the constructor forces you to create a Factory.
The solution given by the article to the problem of injecting runtime data into components is to let runtime data flow through method calls on an initialized object graph by either:
pass runtime data through method calls of the API, or
retrieve runtime data from specific abstractions that allow resolving runtime data.
When runtime data is not used during object graph construction, the component can be created using DI inside the Composition Root and you problem therefore goes away.
Doing so however is not always feasible, and when it isn't, an Abstract Factory is the solution.
Since Object Composition should solely take place in the application's Composition Root however, this means that your Abstract Factory must be an Abstraction. Only this way can you prevent that the construction of your AssetsDownloadingProcess component takes place inside the Composition Root.
The way to do this is to:
Define an abstraction, i.e. IAssetsDownloadingProcessFactory in the application layer where the consumers of this factory live.
Create an implementation of this abstraction inside the Composition Root.
Not using an abstraction means that consumers will take a dependency on the concrete AssetsDownloadingProcessFactory class (which is a Dependency Inversion Principle violation) and it pulls the object composition out of the Composition Root. This will cause object composition to be scattered throughout the application, which hinders maintainability.

How do I make Simple Injector prefer implementations of the "most derived" interface?

In my data access layer I have a repository hierarchy that looks like this:
<TEntity>
IEntityRepository<---------+ICustomerRepository
^ ^
| |
| |
| |
+ |
<TEntity> +
EntityRepository<----------+CustomerRepository
The IEntityRepository<TEntity> interface defines basic CRUD operations that will be useful regardless of entity type. EntityRepository<TEntity> is a concrete implementation of these operations.
In addition, there are repository types for operations that are specific to a particular entity. In the example above, I have a Customer entity, and the ICustomerRepository interface defines operations such as GetByPhoneNumber. The ICustomerRepository also derives from IEntityRepository<Customer>, so that the common CRUD operations will also be available for an instance of ICustomerRepository. Finally, CustomerRepository is the concrete implementation for the ICustomerRepository operations, and it also inherits from EntityRepository<Customer> for the common operations implementation.
So, going over to my actual question: I use Simple Injector to inject instances into my application. I register each of the specialized repository types in my container: CustomerRepository as the implementation of ICustomerRepository and so on.
To ensure new entity types can be added to the system and used without needing to create a new, concrete repository implementation as well, I would like to be able to serve the base EntityRepository<> implementation when an IEntityRepository<> of the new entity is requested. I've understood I can use the RegisterOpenGeneric method for this.
What I can't figure out is, when a generic repository is requested, how can I serve the specialized repository for that type if it exists, and the generic repository only as a fallback?
For example, let's say I do this in my application:
container.Register<ICustomerRepository, CustomerRepository>();
container.RegisterOpenGeneric(typeof(IEntityRepository<>), typeof(EntityRepository<>));
Most of the classes relying on repositories would request the ICustomerRepositorydirectly. However, there could be a class in my application requesting the base interface, like this:
public ContractValidator(IEntityRepository<Customer> customerRepository,
IEntityRepository<Contract> contractRepository)
{
...
What happens in the example above is:
customerRepository gets an instance of EntityRepository<Customer>
contractRepository gets an instance of EntityRepository<Contract>
What I want to happen is:
customerRepository gets an instance of CustomerRepository
contractRepository gets an instance of EntityRepository<Contract>
Is there any way to inform Simple Injector's resolution that if a derivation of a particular interface exists, this should be served instead? So for IDerived : IBase, requests for IBase should return an implementation of IDerived if it exists. And I don't want this resolution across the board, just for these repositories. Can it be done in a reasonable way, or would I need to manually iterate through all the registrations in the RegisterOpenGeneric predicate and check manually?
Assuming your classes look like this
public class CustomerRepository :
ICustomerRepository,
IEntityRepository<Customer> { }
You can register all the generic implementations of IEntityRepository<> using RegisterManyForOpenGeneric and the fallback registration stays the same.
UPDATE: Updated with v3 syntax
// Simple Injector v3.x
container.Register<ICustomerRepository, CustomerRepository>();
container.Register(
typeof(IEntityRepository<>),
new[] { typeof(IEntityRepository<>).Assembly });
container.RegisterConditional(
typeof(IEntityRepository<>),
typeof(EntityRepository<>),
c => !c.Handled);
// Simple Injector v2.x
container.Register<ICustomerRepository, CustomerRepository>();
container.RegisterManyForOpenGeneric(
typeof(IEntityRepository<>),
new[] { typeof(IEntityRepository<>).Assembly });
container.RegisterOpenGeneric(
typeof(IEntityRepository<>),
typeof(EntityRepository<>));
But you should note that if you use any lifestyle then these separate registrations may not resolve as you would expect. This is known as a torn lifestyle.
You can't use RegisterOpenGeneric or RegisterManyForOpenGeneric for this. You will have to hand-write some code to reflect over the type system and find the implementations to register by their specific interface.
In my opinion however you should not have custom repository. These one-to-obe mappings are cause you these grief and besides, you are violating the SOLID principles by doing so. If you can, consider a design as described here.

Why does one use dependency injection?

I'm trying to understand dependency injections (DI), and once again I failed. It just seems silly. My code is never a mess; I hardly write virtual functions and interfaces (although I do once in a blue moon) and all my configuration is magically serialized into a class using json.net (sometimes using an XML serializer).
I don't quite understand what problem it solves. It looks like a way to say: "hi. When you run into this function, return an object that is of this type and uses these parameters/data."
But... why would I ever use that? Note I have never needed to use object as well, but I understand what that is for.
What are some real situations in either building a website or desktop application where one would use DI? I can come up with cases easily for why someone may want to use interfaces/virtual functions in a game, but it's extremely rare (rare enough that I can't remember a single instance) to use that in non-game code.
First, I want to explain an assumption that I make for this answer. It is not always true, but quite often:
Interfaces are adjectives; classes are nouns.
(Actually, there are interfaces that are nouns as well, but I want to generalize here.)
So, e.g. an interface may be something such as IDisposable, IEnumerable or IPrintable. A class is an actual implementation of one or more of these interfaces: List or Map may both be implementations of IEnumerable.
To get the point: Often your classes depend on each other. E.g. you could have a Database class which accesses your database (hah, surprise! ;-)), but you also want this class to do logging about accessing the database. Suppose you have another class Logger, then Database has a dependency to Logger.
So far, so good.
You can model this dependency inside your Database class with the following line:
var logger = new Logger();
and everything is fine. It is fine up to the day when you realize that you need a bunch of loggers: Sometimes you want to log to the console, sometimes to the file system, sometimes using TCP/IP and a remote logging server, and so on ...
And of course you do NOT want to change all your code (meanwhile you have gazillions of it) and replace all lines
var logger = new Logger();
by:
var logger = new TcpLogger();
First, this is no fun. Second, this is error-prone. Third, this is stupid, repetitive work for a trained monkey. So what do you do?
Obviously it's a quite good idea to introduce an interface ICanLog (or similar) that is implemented by all the various loggers. So step 1 in your code is that you do:
ICanLog logger = new Logger();
Now the type inference doesn't change type any more, you always have one single interface to develop against. The next step is that you do not want to have new Logger() over and over again. So you put the reliability to create new instances to a single, central factory class, and you get code such as:
ICanLog logger = LoggerFactory.Create();
The factory itself decides what kind of logger to create. Your code doesn't care any longer, and if you want to change the type of logger being used, you change it once: Inside the factory.
Now, of course, you can generalize this factory, and make it work for any type:
ICanLog logger = TypeFactory.Create<ICanLog>();
Somewhere this TypeFactory needs configuration data which actual class to instantiate when a specific interface type is requested, so you need a mapping. Of course you can do this mapping inside your code, but then a type change means recompiling. But you could also put this mapping inside an XML file, e.g.. This allows you to change the actually used class even after compile time (!), that means dynamically, without recompiling!
To give you a useful example for this: Think of a software that does not log normally, but when your customer calls and asks for help because he has a problem, all you send to him is an updated XML config file, and now he has logging enabled, and your support can use the log files to help your customer.
And now, when you replace names a little bit, you end up with a simple implementation of a Service Locator, which is one of two patterns for Inversion of Control (since you invert control over who decides what exact class to instantiate).
All in all this reduces dependencies in your code, but now all your code has a dependency to the central, single service locator.
Dependency injection is now the next step in this line: Just get rid of this single dependency to the service locator: Instead of various classes asking the service locator for an implementation for a specific interface, you - once again - revert control over who instantiates what.
With dependency injection, your Database class now has a constructor that requires a parameter of type ICanLog:
public Database(ICanLog logger) { ... }
Now your database always has a logger to use, but it does not know any more where this logger comes from.
And this is where a DI framework comes into play: You configure your mappings once again, and then ask your DI framework to instantiate your application for you. As the Application class requires an ICanPersistData implementation, an instance of Database is injected - but for that it must first create an instance of the kind of logger which is configured for ICanLog. And so on ...
So, to cut a long story short: Dependency injection is one of two ways of how to remove dependencies in your code. It is very useful for configuration changes after compile-time, and it is a great thing for unit testing (as it makes it very easy to inject stubs and / or mocks).
In practice, there are things you can not do without a service locator (e.g., if you do not know in advance how many instances you do need of a specific interface: A DI framework always injects only one instance per parameter, but you can call a service locator inside a loop, of course), hence most often each DI framework also provides a service locator.
But basically, that's it.
P.S.: What I described here is a technique called constructor injection, there is also property injection where not constructor parameters, but properties are being used for defining and resolving dependencies. Think of property injection as an optional dependency, and of constructor injection as mandatory dependencies. But discussion on this is beyond the scope of this question.
I think a lot of times people get confused about the difference between dependency injection and a dependency injection framework (or a container as it is often called).
Dependency injection is a very simple concept. Instead of this code:
public class A {
private B b;
public A() {
this.b = new B(); // A *depends on* B
}
public void DoSomeStuff() {
// Do something with B here
}
}
public static void Main(string[] args) {
A a = new A();
a.DoSomeStuff();
}
you write code like this:
public class A {
private B b;
public A(B b) { // A now takes its dependencies as arguments
this.b = b; // look ma, no "new"!
}
public void DoSomeStuff() {
// Do something with B here
}
}
public static void Main(string[] args) {
B b = new B(); // B is constructed here instead
A a = new A(b);
a.DoSomeStuff();
}
And that's it. Seriously. This gives you a ton of advantages. Two important ones are the ability to control functionality from a central place (the Main() function) instead of spreading it throughout your program, and the ability to more easily test each class in isolation (because you can pass mocks or other faked objects into its constructor instead of a real value).
The drawback, of course, is that you now have one mega-function that knows about all the classes used by your program. That's what DI frameworks can help with. But if you're having trouble understanding why this approach is valuable, I'd recommend starting with manual dependency injection first, so you can better appreciate what the various frameworks out there can do for you.
As the other answers stated, dependency injection is a way to create your dependencies outside of the class that uses it. You inject them from the outside, and take control about their creation away from the inside of your class. This is also why dependency injection is a realization of the Inversion of control (IoC) principle.
IoC is the principle, where DI is the pattern. The reason that you might "need more than one logger" is never actually met, as far as my experience goes, but the actually reason is, that you really need it, whenever you test something. An example:
My Feature:
When I look at an offer, I want to mark that I looked at it automatically, so that I don't forget to do so.
You might test this like this:
[Test]
public void ShouldUpdateTimeStamp
{
// Arrange
var formdata = { . . . }
// System under Test
var weasel = new OfferWeasel();
// Act
var offer = weasel.Create(formdata)
// Assert
offer.LastUpdated.Should().Be(new DateTime(2013,01,13,13,01,0,0));
}
So somewhere in the OfferWeasel, it builds you an offer Object like this:
public class OfferWeasel
{
public Offer Create(Formdata formdata)
{
var offer = new Offer();
offer.LastUpdated = DateTime.Now;
return offer;
}
}
The problem here is, that this test will most likely always fail, since the date that is being set will differ from the date being asserted, even if you just put DateTime.Now in the test code it might be off by a couple of milliseconds and will therefore always fail. A better solution now would be to create an interface for this, that allows you to control what time will be set:
public interface IGotTheTime
{
DateTime Now {get;}
}
public class CannedTime : IGotTheTime
{
public DateTime Now {get; set;}
}
public class ActualTime : IGotTheTime
{
public DateTime Now {get { return DateTime.Now; }}
}
public class OfferWeasel
{
private readonly IGotTheTime _time;
public OfferWeasel(IGotTheTime time)
{
_time = time;
}
public Offer Create(Formdata formdata)
{
var offer = new Offer();
offer.LastUpdated = _time.Now;
return offer;
}
}
The Interface is the abstraction. One is the REAL thing, and the other one allows you to fake some time where it is needed. The test can then be changed like this:
[Test]
public void ShouldUpdateTimeStamp
{
// Arrange
var date = new DateTime(2013, 01, 13, 13, 01, 0, 0);
var formdata = { . . . }
var time = new CannedTime { Now = date };
// System under test
var weasel= new OfferWeasel(time);
// Act
var offer = weasel.Create(formdata)
// Assert
offer.LastUpdated.Should().Be(date);
}
Like this, you applied the "inversion of control" principle, by injecting a dependency (getting the current time). The main reason to do this is for easier isolated unit testing, there are other ways of doing it. For example, an interface and a class here is unnecessary since in C# functions can be passed around as variables, so instead of an interface you could use a Func<DateTime> to achieve the same. Or, if you take a dynamic approach, you just pass any object that has the equivalent method (duck typing), and you don't need an interface at all.
You will hardly ever need more than one logger. Nonetheless, dependency injection is essential for statically typed code such as Java or C#.
And...
It should also be noted that an object can only properly fulfill its purpose at runtime, if all its dependencies are available, so there is not much use in setting up property injection. In my opinion, all dependencies should be satisfied when the constructor is being called, so constructor-injection is the thing to go with.
I think the classic answer is to create a more decoupled application, which has no knowledge of which implementation will be used during runtime.
For example, we're a central payment provider, working with many payment providers around the world. However, when a request is made, I have no idea which payment processor I'm going to call. I could program one class with a ton of switch cases, such as:
class PaymentProcessor{
private String type;
public PaymentProcessor(String type){
this.type = type;
}
public void authorize(){
if (type.equals(Consts.PAYPAL)){
// Do this;
}
else if(type.equals(Consts.OTHER_PROCESSOR)){
// Do that;
}
}
}
Now imagine that now you'll need to maintain all this code in a single class because it's not decoupled properly, you can imagine that for every new processor you'll support, you'll need to create a new if // switch case for every method, this only gets more complicated, however, by using Dependency Injection (or Inversion of Control - as it's sometimes called, meaning that whoever controls the running of the program is known only at runtime, and not complication), you could achieve something very neat and maintainable.
class PaypalProcessor implements PaymentProcessor{
public void authorize(){
// Do PayPal authorization
}
}
class OtherProcessor implements PaymentProcessor{
public void authorize(){
// Do other processor authorization
}
}
class PaymentFactory{
public static PaymentProcessor create(String type){
switch(type){
case Consts.PAYPAL;
return new PaypalProcessor();
case Consts.OTHER_PROCESSOR;
return new OtherProcessor();
}
}
}
interface PaymentProcessor{
void authorize();
}
** The code won't compile, I know :)
The main reason to use DI is that you want to put the responsibility of the knowledge of the implementation where the knowledge is there. The idea of DI is very much inline with encapsulation and design by interface.
If the front end asks from the back end for some data, then is it unimportant for the front end how the back end resolves that question. That is up to the requesthandler.
That is already common in OOP for a long time. Many times creating code pieces like:
I_Dosomething x = new Impl_Dosomething();
The drawback is that the implementation class is still hardcoded, hence has the front end the knowledge which implementation is used. DI takes the design by interface one step further, that the only thing the front end needs to know is the knowledge of the interface.
In between the DYI and DI is the pattern of a service locator, because the front end has to provide a key (present in the registry of the service locator) to lets its request become resolved.
Service locator example:
I_Dosomething x = ServiceLocator.returnDoing(String pKey);
DI example:
I_Dosomething x = DIContainer.returnThat();
One of the requirements of DI is that the container must be able to find out which class is the implementation of which interface. Hence does a DI container require strongly typed design and only one implementation for each interface at the same time. If you need more implementations of an interface at the same time (like a calculator), you need the service locator or factory design pattern.
D(b)I: Dependency Injection and Design by Interface.
This restriction is not a very big practical problem though. The benefit of using D(b)I is that it serves communication between the client and the provider. An interface is a perspective on an object or a set of behaviours. The latter is crucial here.
I prefer the administration of service contracts together with D(b)I in coding. They should go together. The use of D(b)I as a technical solution without organizational administration of service contracts is not very beneficial in my point of view, because DI is then just an extra layer of encapsulation. But when you can use it together with organizational administration you can really make use of the organizing principle D(b)I offers.
It can help you in the long run to structure communication with the client and other technical departments in topics as testing, versioning and the development of alternatives. When you have an implicit interface as in a hardcoded class, then is it much less communicable over time then when you make it explicit using D(b)I. It all boils down to maintenance, which is over time and not at a time. :-)
Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH environment variable (or other language equivalent, like PYTHONPATH, LD_LIBRARY_PATH) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like
var logger = new Logger() //sane, simple code
And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.
No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.
P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.

In dependency Injection what is a dependency?

I'he read a lot about this but still i am unclear about the things. We say that DI means injecting dependencies into dependent components at runtime
Q1
What is a dependency ? If these are the objects created at runtime?
If yes, does that mean we are injecting values into variables by creating an object(created by framework i.e instantianting the bean via xml file with setter/constructor injection)
Q2
We do the DI to do work without object intervention?
Q1
From Wikipedia, all elements in DI pattern are objects. The dependent object specifies what it needs using interfaces. The injector object decides what concrete classes (instantiated objects) can satisfy the requirement and provide them to the dependent object.
So, that becomes a yes to the second part.
Q2
Again from Wikipedia:
The primary purpose of the dependency injection pattern is to allow
selection among multiple implementations of a given dependency
interface at runtime, or via configuration files, instead of at
compile time.
As an example consider a security service that can work different implementations of an Encoder. The different encoding algorithm could include SHA, MD5 and others. The security service only specifies that it needs an instance of "an encoding algorithm". The runtime DI environment then will look to find an object that is providing the interface of Encoder and then injects to the security service. In line with DI, the security service is also taking advantage of Inversion of Control (IoC); i.e. it does not itself decide what implementation to use but it is the DI runtime that takes that decision.
Not a elaborate answer to make it just simpler.
Ques1:
class Dependent {
propertyA = new PropertyA();
propertyB = new PropertyB();
}
Here Dependent is dependent to propertyA and propertyB. Above relation is an example of dependency.
If these are the objects created at runtime? Yes.
If yes....? Yes too
Ques2: Yes.
Detail is included below
Scenario 1:
class Dependent {
DBConnection connection = new OracleConnection();
}
Dependent class is highly coupled. Since there is no way to change the connection unless we change the code. So if customer need MySQLConnection() we will have to change the code and give them another exe/jar.
Scenario 2:
class Dependent {
DBConnection connection = ConnectionFactory.createConnection();
}
This is much better since, ConnectionFactory will be able to read some configuration and create necessary connection.
But still, it raises some difficulty to mock the Dependent class. It is hard to create mock in these scenarios. Then what?
Scenario 3:
class Dependent {
DBConnection connection;
setConnection(DBConnection connection) {
this.connecttion = connection;
}
}
class DependencyInjector {
inject() {
// wire them together every dependent & their dependency!
Dependent dependent = indentiyDepenentSomeSmartWay();
DBConnection connection = indentiyConnectionSomeSmartWay();
dependent.setConnection(connection);
}
}
Our DependencyInjector is a smart class, know all the necessary information! Above Dependent class is clean & simple. It is easy mock them for unit test, configurable using configuration.
Those object creation & coupling is detached!
To answer your questions in simple words,
For #1 :
Dependency injection is something about satisfying the need of one object by giving it the object it requires.
Let see an example :
Generally in an enterprise application we use an architecture where in services call a DAO layer and DAO does all the database related stuff. So service need and object of DAO to call all the DAO methods.
Considering we have an entity object - Person.
Lets say we have a DAO - PersonDAO.
public interface PersonDAO {
void addPerson(Person person);
void updatePerson(Person person);
void deletePerson(int personId);
}
and a service - PersonService.
public class PersonServiceImpl {
private PersonDAO personDAO;
public void addPerson() {
//some code specific to service.
//some code to create Person obj.
personDAO.add(person);
}
}
As you can see PersonService is using PersonDAO object to call its methods. PersonService depends on PersonDAO. So PersonDAO is dependency and PersonService is dependent object.
Normally in frameworks like Spring these dependencies are injected by frameworks itself. When application context is loaded all these dependency objects are created and put in Container and whenever needed they are used. The concept of Inversion of Control(IoC) is very closely related to Dependency Injection because of the way the dependency object is created.
E.g You could have created the PersonDAO object in PersonService itself as
PersonDAO personDAO = new PersonDAOImpl();
But in case of spring you are just defining a property for PersonDAO in PersonService and providing a setter for it which is used by spring to set the dependency. Here the creation of dependency is taken care by framework instead of the class which is using it hence it is called Inversion of Control.
For #2 : Yes. You are right.

Is it possible to pass arguments to Symony2 container constructor

When creating an service container in Symfony2 you mostly pass "static" arguments (like other classes etc.) to its constructor.
However I'd like to create a factory and therefore I need to be able to pass an dynamic argument to the service constructor.
The examples I found ( e.g. http://symfony.com/doc/current/cookbook/service_container/factories.html) are all ending up using static arguments as argument.
But what do I have to do, if I want my factory to decide which object to return based on (for example) user input?
I have some problems understanding why service factory should not work on your case. Do you need to return different service class unrelated to each other?
What I see from the factory example is that you could do something like this:
class NewsletterFactory
{
public function __constructor(...)
{
// Receive arguments needed to create the service below
}
public function get()
{
// Say the variable $userInput exists and is derived from constructor
if ($userInput === 'string')
return new NewsletterManager($dynamicArgument1);
if ($userInput === 'integer')
return new AnotherNewsletterManager($dynamicArgument2);
return new DefaultNewsletterManager();
}
}
Now, if this doesn't fit your needs. You can also create a service say CustomFactory that returns what you need. What is returned is not directly a service, so you can do whatever you want. But this would prevent you from requesting the objects created by CustomFactory from the dependency container.
Similar to that is the FormFactory. It is the factory used to instantiate form type. But the FormFactory is more powerfull since it is coupled with a dependency injection tag and a compiler pass, which register each types into the dependency injection system so they can be retrieved on their own. I don't exactly all the internals of the Form component but I think it could solve your problem if other methods do not.
Regards,
Matt

Resources