user107986
user107986

Reputation: 1541

Dependency injection example

There's a nice tutorial that seems to make sense about DI and IoC

Wouldn't it be easier to make the getCustomer methods static in the injector classes? I don't really see any reason to instantiate injector objects in this case.

So instead of:

MessageServiceInjector injector = null;
Consumer app = null;

injector = new EmailServiceInjector();
app = injector.getConsumer();
app.processMessages(msg, email);

We would just do:

Consumer app = null;
app = EmailServiceInjector.getConsumer();
app.processMessages(msg, email);

How to write injector classes properly? At the end of the article it says

We can achieve IoC through Factory Pattern, Template Method Design Pattern, Strategy Pattern and Service Locator pattern too

but I guess none of the patterns was used in this example (IoC in this case is just simplistic). So how would it be done in a real project (assuming no external frameworks or IoC containers are used), i.e. if I wanted to create all the necessary stuff to let me use DI in my code.

Upvotes: 1

Views: 679

Answers (3)

Yacoub Massad
Yacoub Massad

Reputation: 27871

Wouldn't it be easier to make the getCustomer methods static in the injector classes?

It seems to me that what this article is calling an Injector is actually an abstract factory. We use abstract factories when we want a class to create objects at a later point it time.

In general it is not recommended to have static methods. Mainly because the classes that call the static method will have a hard dependency on it, i.e., you cannot at a later point in time consume a different dependency without changing the consuming class code. And this is exactly the problem that DI is trying to solve.

Another reason is that it is hard to mock static methods in a unit test.

So how would it be done in a real project?

In real projects you should construct your objects (e.g. services) in the composition root.

There are two ways to do it. Either use a DI container, or use Pure DI.

In my opinion, Pure DI is a better choice. See this article for a reason why.

Upvotes: 1

Rahul Teke
Rahul Teke

Reputation: 11

In real world project, you should use Dependency injection framework like Spring Framework. The are other as well likeGoogle Guice.

I have been personally using spring for couple of years now and it has grow to much larger extent apart from basic DI.

Upvotes: 1

duffymo
duffymo

Reputation: 309028

"Easier"? I don't think it makes any difference to your DI engine.

Static would assume one instance. What if you want an instance per request, as you might for each web request? Static won't do then.

I've used Spring for more than ten years. It has a bean factory and DI capability that can deal with singleton or per request instances. Have a look at how it works to see one successful way to do it.

I think Martin Fowler's DI article, now 11 years old, still explains it well.

Upvotes: 2

Related Questions