Luca Fülbier
Luca Fülbier

Reputation: 2731

DI containers and concrete values / configuration data

I have read a bit about DI and DI containers that manage the DI for you.

Basically you create your classes that have dependencies, and provide a way for injection using the constructor or setter methods. You then tell your DI container, which concrete classes you want to use for wiring everything together. Lastly you make a call to some kind of service locator, that resolves all the dependencies for you and gives you the complex object with just one line of code.

I have never used a concrete DI container implementation, so i wonder how a DI container handles the objects at the lowest level. These objects most likely have to be configured using concrete (coded) values, or the content of a configuration file. Take this for example:

class FooDao {
    public FooDao(DBConnection db) {...}
}

class ConcreteDBConnection : DBConnection {
    public ConcreteDBConnection(String url, int port, String user, String pw)
    {...}
}

You would tell your DI container (using annotations, XML files, or something else), that you want to instantiate your FooDao objects with a ConcreteDBConnection object. But how do you tell your DI container the concrete values needed for your database connection? What if the concrete values need to be calculated first (encrypting locally stored database connection information for example)?

I know this is a very general question, but the articles i read about DI container were also very general and this point really confused me. A short explanation how a arbitrary popular DI framework does this would be enough to answer my question.

Upvotes: 1

Views: 80

Answers (1)

daf
daf

Reputation: 1329

If you're asking how to use a popular DI container, there are a lot of articles on using Castle Windsor (such as http://ardalis.com/getting-started-with-castle-windsor) and the concepts will be familiar when you try other DI frameworks. Castle Windsor is really good though -- it's a great place to start.

If you're asking how DI containers work -- that's a longer discussion, but the basics are: 1. You create a container of some kind, using your framework. Normally as simple as var container = new Container(); 1. You register a mapping of interface ("service") to concrete classes with the container. Some frameworks have some magic to do a lot of this for you, like the most common requirement: if you have an interface IFoo and only one resolution, the class Foo, then it can be automatically registered for you (iirc, Autofac does this?) 2. You ask your container to resolve interfaces -- which it maps back to classes. During resolution, your container can inspect constructors of the provided concrete classes and attempt to resolve parameters based on their types; similarly, it can set properties based on their types and the known registrations.

Upvotes: 1

Related Questions