views:

172

answers:

4

I've been reading about dependency injection and have a simple question. I can understand how via constructor or setter injection required dependencies are autowired by the DI framework. What happens when an object decides it needs to create a new object due to some business process? Do I need to always create a Factory in these situations? To make it a less abstract question, here is an example.

Let's say I'm writing a game of Asteriods. There's a ship in the middle which can spin around and shoot the asteriods. Assume that the ship has been created and approriate things injected. When playerShip.shoot() is called we need to create a bullet object. The bullet object needs to know which way it is going (direction) and where to start (point).

Normally, I would do something like this:

bullet = new Bullet( direction, point );

However, that tightly couples the PlayerShip class to the Bullet class. How should this work under dependency injection? Do I need to create a BulletFactory interface and inject an implementation of that into the ship?

Edit: I'm not actually writing asteriods. This was a simple example that I thought people would understand. I wanted something that needed to be created a runtime (not while "wiring up objects") that also had parameters to it's constructor.

+2  A: 

The dependency injection is not suitable for this case. If you create a factory for this you will overuse design patterns. You can't decouple the entire system, in this case Ship has a composition with Bullet, and in case you need any more complex than that another pattern (not necessarily DI) might be adequate.

victor hugo
So, only use DI for service type objects and singletons?
WW
+2  A: 

Depends if you just going to have just one bullet type...

If just one then I would say you'd be ok.

But if you have a Bullet, DoubleBullet, PowerBullet, NukeBullet, etc.

Then I would make Bullet base class and all the other Derrived from it

Then I would make Bullet factory and it would have CreateBullet, CreatePowerBullet, etc.

The other question is will anything else be making a bullet? If so then I would create a factory to consolidate the creation logic in one place...

Otherwise it smells like your using DI just to be using DI...

J.13.L
+1  A: 

Yes, this smells like over-architecting. Nevertheless, off the top of my head, you could have a property that stores the bullet Type and then have your DI framework (ninject here) create the bullet.

public Type BulletType {get; set;}

public void fire()
{
    var b = (BulletType) kernel.get(BulletType);
    b.fire(point, direction);
}
Ray
So kernel.get(BulletType) will lookup the class name I've specified externally and create me an instance of that? Does this mean that point and direction can not be passed in the constructor but have to be set subsequent to creation?
WW
Ray
+1  A: 
Ross