code_junkie

Unity Application Block, inherited injection

Nov 12th, 2011
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. UniversalComposition universe = new UniversalComposition();
  6.  
  7.  
  8. }
  9. }
  10.  
  11. public class UniversalComposition : Composition
  12. {
  13. // Everything that gets resolved in this container should contain a child container created by the this container
  14.  
  15. public UniversalComposition()
  16. {
  17. this.Container.RegisterType<IService, Service>();
  18. }
  19.  
  20. protected override IUnityContainer CreateContainer()
  21. {
  22. return new UnityContainer();
  23. }
  24.  
  25. }
  26.  
  27. public abstract class Composition
  28. {
  29. protected IUnityContainer Container {get; private set;}
  30.  
  31. public Composition()
  32. {
  33. this.Container = this.CreateContainer();
  34. }
  35.  
  36. public TInstance Resolve<TInstance>()
  37. {
  38. return this.Container.Resolve<TInstance>();
  39. }
  40.  
  41. protected abstract IUnityContainer CreateContainer();
  42. }
  43.  
  44. public class Service : Composition, IService
  45. {
  46. public Service(/* I want to inject a child Unity Container in here container.CreateChildContainer() */)
  47. {
  48. }
  49. }
  50.  
  51. public interface IService { }
  52.  
  53. public abstract class BaseClass
  54. {
  55. public IUnityContainer Container { get; protected set; }
  56.  
  57. public BaseClass() : BaseClass(null) {}
  58.  
  59. public BaseClass( IUnityContainer container )
  60. {
  61. this.container = container ?? this.CreateContainer();
  62. }
  63.  
  64. public abstract IUnityContainer CreateContainer();
  65. }
  66.  
  67. public class DerivedClass : BaseClass
  68. {
  69. public IUnityContainer ChildContainer { get; private set; }
  70.  
  71. public DerivedClass() : DerivedClass(null,null) {}
  72.  
  73. public DerivedClass( IUnityContainer parent, IUnityContainer child )
  74. : BaseClass( parent )
  75. {
  76. this.ChildContainer = child ?? this.CreateChildContainer();
  77. }
  78.  
  79. public IUnityContainer CreateContainer()
  80. {
  81. return new UnityContainer();
  82. }
  83.  
  84. public IUnityContainer CreateChildContainer()
  85. {
  86. return this.Container.CreateChildContainer();
  87. }
  88.  
  89. }
Add Comment
Please, Sign In to add comment