Integrating Ninject with Xna 4.0 - dependency-injection

Trying to integrate Ninject with XNA however I am having a bit of pain trying to get it all hooked up.
The problem is I am trying to do it as I think it should done, so I am decoupling things as much as possible to make it more modular, and Xna isn't happy with me doing this... an example of this is where the Game object news up a lot of things internally, and a lot of those things could do with being passed around to my objects. So I decided to add these as constructor arguments to the Game class, so I can setup all the dependencies then use Ninject to give me the Game instance with all its dependencies resolved.
Unfortunately In this example normally XNA doesn't new up its SpriteBatch until it has gotten to the Initilize stage, which I assume is because it needs the GraphicsDeviceManager to get the window handle to create the GraphicsDevice before it can be exposed for anything to use...
So because of this they cannot be injected into the game because it needs to do its stuff first, and I cannot really push them in after the game is made, because I need other things like the World component to be injected with things as well and pushed into the game.
At this point I thought maybe I could create my own GraphicsDevice, but as I need the handle I would need to make my own window too, which I later realised XNA would dispose and recreate anyway. So it leaves me with a horrible taste in my mouth... as I dont fancy re-writing the Game and GraphicsDeviceManager classes, which would require me to re-write lots of other functionality as they are all internal to the XNA assembly...
So has anyone managed to setup their dependency injection without having to re-write large chunks of XNA?
Here is an example of my current module:
public class XnaModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IServiceProvider>().To<NinjectServiceProvider>().InSingletonScope();
Kernel.Bind<IGraphicsDeviceService>().To<GraphicsDeviceManager>().InSingletonScope();
Kernel.Bind<ContentManager>().ToSelf().InSingletonScope();
Kernel.Bind<SpriteBatch>().ToSelf().InSingletonScope();
var contentManager = new ContentManager(Kernel.Get<IServiceProvider>());
contentManager.RootDirectory = "Content";
Kernel.Bind<ContentManager>().ToConstant(contentManager).InSingletonScope();
var game = new MyGame(Kernel.Get<IGraphicsDeviceService>() as GraphicsDeviceManager,
Kernel.Get<SpriteBatch>(), contentManager);
Kernel.Bind<Game>().ToConstant(game).InSingletonScope();
}
}
Then the game constructor:
public class MyGame : Game
{
public SpriteBatch SpriteBatch { get; private set; }
public GraphicsDeviceManager Graphics { get; private set; }
public MyGame(GraphicsDeviceManager graphics, SpriteBatch spriteBatch, ContentManager contentManager)
{
Graphics = graphics;
SpriteBatch = spriteBatch;
Content = contentManager;
}
// Other stuffs
}
Both are just examples so you can see the sort of approach I am taking, the module bypasses the circular dependency issue as I new the game up myself. And I have excluded the GameModule, which would contain the dependencies for my actual Game objects, i.e factories, gui components etc, and the problem is they ultimately need to be injected into the Game too, and we then we have a catch22.
As they cannot be injected until the dependencies are resolved, but you cannot resolve the dependencies until you have started the game... it seems a lose/lose situation. So can anyone tell me how they got round this issue?
I did find http://steveproxna01di.codeplex.com/ but was looking if there are any more examples as this is more of a service locator approach, rather than an Injection approach.

As no one has answered this, I will put in that I basically turned my Game instance into a wrapper and bootstrapper for a custom IGame instance which is the root injection point. This way I am able to inject whatever I want.

Related

Some concepts in Dependency Injection

I am new to dependency injection and have been doing some reading about it, both on StackOverflow and elsewhere. In practice I am having trouble with using it correctly.
To explain the problem, here's a basic situation where I am not sure how to use DI:
Suppose I have some object that is going to be used in several different classes. However, in order for this object to be usable, it needs certain parameters that I don't have at start-up.
A conceivable way that I can see to do this using DI is to create a blank instance of this object, a method to initialize it with the necessary parameters, and a flag for whether or not it is initialized.
To me, this feels like a hack, because the object shouldn't really exist yet and I am just passing a container around, waiting for the responsible code to initialize it. Is this how it is meant to be done, or am I missing the point?
That is indeed a pretty tough thing to get one's head around when getting started with DI, and something that also isn't easily explained.
Your notion that creating a "blank" object that will be initialized later via a method might be a suboptimal solution is correct - an object should be able to do its work at any time; Initialize() methods are what Mark Seemann calls "temporal coupling" in his book Dependency Injection in .NET. This is an anti-pattern that makes the code using the object dependent on the inner workings of that object and thus breaks encapsulation.
The question is when the required information becomes available, what the "responsible code to initialize it" is, and where it gets the information from - and also how it gets access to the object to initialize it. Ideally, this initializing code would itself be injected into your object, and whenever your object's methods/properties are accessed, it requests initialization from that other dependency.
Also, what happens if the IsInitialized flag returns false? Is that still a valid program state?
In general, as an object in a dependency injected object graph, I should either know all my "configuration" data on creation, or know someone who can give it to me (that someone is another object injected as a dependency).
It might help if you could provide a bit more detail about what kind of parameters the object needs and where they need to come from.
Edit
What you're describing in your comment is pretty much exactly my first encounter with this kind of issue; there's a question somewhere here on SO that I posted back then.
The important thing is to build individual classes (usually, there may be exceptions, but what those are is a matter of experience) in such a way that you assume everything the class needs is present. When the program is running, there need to be other classes then that make sure that assumption will not fail.
Setter injection is something I generally try not to have to avoid said temporal coupling; according to Mark Seemann, setter injection should usually only be used when you already have a good default in place that you just overwrite through the setter. In this case, though, the object would not be able to function properly without that dependency.
This may not be the most elegant way to do this (I usually have the luxury to apply DI in pretty closed code-only environments without having to worry about a UI), but it would work (kind of - it compiles, but is still pseudo code):
public class MainForm
{
private readonly IDataManager _dataManager;
private readonly IConnectionProvider _connectionProvider;
private readonly IConnectionReceiver _connectionReceiver;
public MainForm(IDataManager dataManager, IConnectionProvider connectionProvider, IConnectionReceiver connectionReceiver)
{
this._dataManager = dataManager;
this._connectionProvider = connectionProvider;
this._connectionReceiver = connectionReceiver;
}
public void btnConnect_Click()
{
IConnection connection = this._connectionProvider.GetConnection();
if (null != connection)
{
this._connectionReceiver.SetConnection(connection);
this.SetFormControlsEnabled(true);
}
}
private void SetFormControlsEnabled(bool doEnable)
{
}
}
public interface IConnectionProvider
{
IConnection GetConnection();
}
public interface IConnectionReceiver
{
void SetConnection(IConnection connection);
}
public interface IConnection
{
IConnectionWebService ConnectionWebService { get; }
}
public class ConnectionBridge : IConnection, IConnectionReceiver
{
private IConnection _connection;
#region IConnectionReceiver Members
public void SetConnection(IConnection connection)
{
this._connection = connection;
}
#endregion IConnectionReceiver Members
#region IConnection Members
public IConnectionWebService ConnectionWebService
{
get { return this._connection.ConnectionWebService; }
}
#endregion
}
public interface IConnectionWebService {}
public interface IDataManager { }
public class DataManager : IDataManager
{
public DataManager(IConnection connection)
{
}
}
So, MainForm is the thing that holds it all together. It starts out with its controls disabled, because it knows they need a working IDataManager and that will (by convention) need a connection. When a "connect" button is clicked, the form asks its IConnectionProvider dependency for a connection. It does not care where that connection comes from; the connection provider might display another form to ask for credentials or maybe just read them from a file.
Then the form knows that the connection has to be passed on to the IConnectionReceiver instance, and after that all controls can be enabled. This is not by any DI principle, this is just how we have defined that MainForm works.
The data manager on the other hand has everything it needs from the start - an IConnection instance. That can't do what it's supposed to do at first, but there is other code preventing that from causing problems.
ConnectionBridge is both a decorator for the actual IConnection instance and an adapter decoupling connection acquisition from connection consumption. It does that by employing the Interface Segregation Principle.
As a note on the side, be aware that while Dependency Injection is an important technique, it is only one of several principles you should follow to write what is known as "clean code". The most well known are the SOLID principles (of which DI is one), but there are others like Command-Query-Separation (CQS), "Don't repeat yourself" (DRY) and the Law of Demeter. On top of all that, practice unit testing, precisely Test Driven Development (TDD). These things really make a tremendous difference - but if you're taking up DI of your own accord, you're already off to a good start.
I agree with what GCATNM said and i would like to add that whenever i feel there is an object like this i go and use one of the Factory pattern variants (be it an Abstract Factory, Static Factory, etc ..) and i would inject the factory with the source of the configuration information for this object. So as Marc Seemann also said and i am not quoting: Factories are a great companion of Dependency Injection and you will need them occasionally.

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.

XNA draw : using one spritebatch at whole game

I am developing an XNA game. This is time I am careful about the architecture. Til today, I have always implemented my own draw method in this way:
public void Draw(SpriteBatch sb, GameTime gameTime)
{
sb.Begin();
// ... to draw ...
sb.End();
}
I was digging the DrawableGameComponent and saw the Draw method comes in this way:
public void Draw(GameTime gameTime)
{
// ...
}
First of all, I know that SpriteBatch can collect many Texture2D between Begin and End, so that it can be useful to sort them, or draw with same Effects.
My question is about the performance and the cost of passing the SpriteBatch. At DrawableGameComponent it is possible to call spritebatch of game object if its spritebatch is public.
What is suggested, what should a xna-game programmer do?
Thanks in advice.
One of the serious disadvantages of DrawableGameComponent is that you're locked into its provided method signature. While there's nothing "wrong", per se, with DrawableGameComponent, do not think of it as the "one true architecture". You're better off thinking of it as an example of a possible architecture.
If you find yourself needing to pass a SpriteBatch (or anything else) to the draw method of a "game component" - the best way is to pass it as an argument. Anything else is convoluted.
Obviously this means that you can't use XNA's provided GameComponent system, and you have to make your own alternative. But this is almost trivial: At its most basic level, it's just a list of some base type that has appropriate virtual methods.
Of course, if you must use GameComponent - or your game is so simple (eg: a prototype) that you don't really care about the architecture - then you can use basically any method you like to get a SpriteBatch to your draw method. They all have disadvantages.
Probably the next-most architecturally robust method is to pass your SpriteBatch instance into the constructor of each of your components. This keeps your components decoupled from your game class.
On the other hand, if you're throwing architecture to the wind, I'd suggest making your MyGame.spriteBatch field public static. This is the simplest way to allow it to be accessed anywhere. It's easy to implement and easy to clean up later when/if you need to.
To answer your question about performance: Anything to do with passing a SpriteBatch around will have almost negligible effect on performance (providing the order of calls to Draw/Begin/End stays the same). Don't worry about it.
(If you see SpriteBatch whatever in code, that represents a reference. A reference is a 32-bit value (in a 32-bit program, which all XNA games are). That's the same size as an int or a float. It's very small and very cheap to pass around/access/etc.)
If you stumbled upon this question you were probably looking at a nice and generic solution. I would suggest you have a look at this:
https://gamedev.stackexchange.com/questions/14217/several-classes-need-to-access-the-same-data-where-should-the-data-be-declared/14232#14232
I felt the need to correct this question because "the best way is to pass it as an argument. Anything else is convoluted." is simply not correct.
Personally i am now doing it this way in my GameBase class:
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
SpriteBatch = new SpriteBatch(GraphicsDevice);
this.Services.AddService(typeof(SpriteBatch), SpriteBatch);
}
Now, since you're adding DrawableGameComponents in the Initialize Method of your Game class you will be able to call
this.Game.Services.GetService(typeof(SpriteBatch))
I'd say that's the cleanest approach to solve the problem.
If the DrawableGameComponent should be part of the parent's SpriteBatch, then just pass it in via the constructor and store it in a private member (or expose it as a property if you wish).
You could also expose the SpriteBatch as a property of your Game class if you wanted, like you suggested, but every time you referenced this.Game, you would need to cast it to your specific Game class type.
((MyGame)this.Game).SpriteBatch.Draw(...)
Or you can just have the DrawableGameComponent create a new SpriteBatch. There's nothing wrong with that (as far as I've ever seen). I suppose it depends how many DrawableGameComponents you'll be creating and how often.
Also browse through the results for a search for DrawableGameComponent - there's a lot of good advice there.

Where is the control inverted in Inversion of Control

I spent lot of time in understanding ioc. I never understand how exactly control is inverted in this pattern. Even I am confused with exact meaning of inversion. In normal english - inversion is some thing like reversing, say reversing a cup.
If I consider dependency injection as Ioc. I would like to know where exactly contol is inverted here. I understand here in DI, dependency is inserted from an external entity with the help of constructor, setter ........
But I never understand where the control is inverted here...
Any help appreciated.
Old style:
Class car
{
Engine _engine;
Public Car()
{
_engine = new V6();
}
}
inverted:
Class car
{
Engine _engine;
Public Car(Engine engine)
{
_engine = engine;
}
}
var car = new Car(new V4());
The caller has the control instead of the car class
Dependency injection inverses control.
For example a car class needs a engine class. The engine could be any type of engine.
If you don't use DI, the car class would determine the engine type itself, the car class is in control.
When using DI, the code instantiating a car would determine the type of car (by specifying the engine in constructor for example), the calling code is now in control. Control is inverted from car class to calling code.
To expand on robin's answer:
IUserRepository _user = new UserRepository();
//you're in control of which instance is created.
With dependency injection:
IUserRepository _user;// you will not do anything else.
Based on a configuration somewhere else, the dependency injection framework you use will take care of creating the right instance for you. This is when control is inversed from your code. You are not directly creating any instance from your code.
Why!? Why would you do this?
One major advantage is testing, when you run tests, you can configure your IUserRepository with a fake one.

Global State and Singletons Dependency injection

This is a problem I face a lot of times when I am designing a new app.
I'll use a sample problem to explain this.
I am writing simple game, so I want to hold a list of players.
I have few options...
Use a static field in some class
private static ArrayList<Player> players = new ArrayList<Integer>();
public Player getPlayer(int i){
return players.get(i);
}
but this a global state
Or I can use a singleton
class PlayerList{
private PlayerList instance;
private PlayerList(){...}
public PlayerList getInstance() {
if(instance==null){
...
}
return instance;
}
}
but this is bad because it's a singleton
Dependency injection
class Game {
private PlayerList playerList;
public Game(PlayerList list) {
this.list = list;
}
public PlayerList getPlayerList() {
return playerList;
}
}
this seems good but it's not.
If any object outside Game need to look at PlayerList (which is the usual case)
I have to use one of the above methods to make the Game class available globally.
so I just add another layer to the problem. I didn't actually solve anything.
What is the optimum solution?
(currently I use Singleton approach)
That's why DI Containers manage lifecycle. Let the Playerlist be a singleton in terms of container lifecycle. Gives you full testability of components and let's the container (not you) get its hands dirty.
The idea behind dependency injection is as the name states to inject dependencies. So whatever object needs to know about the player list will be injected with it.
Usually, it makes a lot of sense to use dependency injection as extensively as possible before switching to dependency lookup or some other mechanism. This will also make it possible to extend the game later to have different player lists for different levels or whatever extension you might think about.
If you need PlayerList outside of Game, maybe Game is the wrong class for this? If any other object needs PlayerList, either they need to have the List injected as well, or maybe you should move the list to this class instead of the Game class.
If you have different lifetimes for Game, PlayerList and other Classes, maybe also consider using a Factory to group them. Check this Google Testing Blog article for details.

Resources