-
Notifications
You must be signed in to change notification settings - Fork 6
ServiceContainer
jonathanpeppers edited this page Mar 16, 2013
·
1 revision
ServiceContainer is a simple IoC container, very similar to what you get with Game.Services in XNA or MonoGame.
Registration is explicit and accessed via a static class, all registrations are singleton.
Here are some examples of registration:
//Our types
interface MyInterface { }
class MyClass : MyInterface { }
//This would register MyClass with the default constructor
ServiceContainer.Register<MyClass>();
//So equivalent to
ServiceContainer.Register<MyClass>(() => new MyClass());
//Also equivalent to
ServiceContainer.Register(typeof(MyClass), () => new MyClass());
//Or if you already have an instance of an object
ServiceContainer.Register(myClass);
//Which is equivalent to
ServiceContainer.Register<MyClass>(() => myClass);
//You can also register interfaces
ServiceContainer.Register<MyInterface>(() => new MyClass());
//To retrieve an instance
MyClass myClass = ServiceContainer.Resolve<MyClass>();
MyInterface myInterface = ServiceContainer.Resolve<MyInterface>();
//Also the same as
MyClass myClass = ServiceContainer.Resolve(typeof(MyClass)) as MyClass;
MyInterface myInterface = ServiceContainer.Resolve(typeof(MyInterface)) as MyInterface;
Other notes:
- Double registrations will just overwrite the previous
- If a type is not found, an exception will be thrown
- Cyclic dependencies will work just fine, no exceptions will be thrown -- just use sparingly for your co-worker's sake