SHARE
TWEET

Svelto-IoC: hierarchical DI container usage example

a guest Jul 8th, 2015 215 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Root Container:
  2.  
  3.         void SetupContainer()
  4.         {
  5.                 container = new Container();
  6.  
  7.                 // input
  8.                 container.BindSelf<GameControls>();
  9.                 container.BindSelf<MouseController>();
  10.                 container.BindSelf<CameraRig>();
  11.  
  12.                 // vehicle builder
  13.                 container.BindSelf<VehicleBuilder>();
  14.         }
  15.  
  16. // Vehicle builder:
  17.  
  18. public class VehicleBuilder : MonoBehaviour
  19. {
  20.         [Inject] IContainer ParentContainer { get; set; }
  21.  
  22.  
  23.         public Vehicle Create()
  24.         {
  25.                 // the "scope" container used to construct just a vehicle
  26.                 var container = CreateScopeContainer(ParentContainer);
  27.                
  28.                 return container.Build<Vehicle>();
  29.         }
  30.  
  31.         IContainer CreateScopeContainer(IContainer parentContainer)
  32.         {
  33.                 var container = new Container(parentContainer);
  34.  
  35.                 container.BindSelf<Vehicle>();
  36.                 container.BindSelf<Motor>();
  37.                 container.BindSelf<VehicleConstraints>();
  38.                 container.BindSelf<VehiclePlayerControl>();
  39.  
  40.                 return container;
  41.         }
  42. }
  43.  
  44.  
  45. // Usage:
  46.  
  47. var vehicleBuilder = rootContainer.Build<VehicleBuilder>();
  48. var vehicle = vehicleBuilder.Create();
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top