PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/V1/CORE/Infrastructure.CrossCutting.IoC/Unity/IoCUnityContainer.cs

#
C# | 214 lines | 109 code | 45 blank | 60 comment | 6 complexity | e34a57db685445e6d23794b740ade4e2 MD5 | raw file
  1. // Microsoft Developer & Platform Evangelism
  2. //===================================================================================
  3. // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
  4. // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
  5. // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
  6. //===================================================================================
  7. // Copyright (c) Microsoft Corporation. All Rights Reserved.
  8. // This code is released under the terms of the MS-LPL license,
  9. // http://microsoftnlayerapp.codeplex.com/license
  10. //===================================================================================
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Configuration;
  14. using Microsoft.Practices.Unity;
  15. using Microsoft.Samples.NLayerApp.Application.MainModule.BankingManagement;
  16. using Microsoft.Samples.NLayerApp.Application.MainModule.CustomersManagement;
  17. using Microsoft.Samples.NLayerApp.Application.MainModule.SalesManagement;
  18. using Microsoft.Samples.NLayerApp.Domain.MainModule.BankAccounts;
  19. using Microsoft.Samples.NLayerApp.Domain.MainModule.Countries;
  20. using Microsoft.Samples.NLayerApp.Domain.MainModule.Customers;
  21. using Microsoft.Samples.NLayerApp.Domain.MainModule.Orders;
  22. using Microsoft.Samples.NLayerApp.Domain.MainModule.Products;
  23. using Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.Resources;
  24. using Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.Unity.LifetimeManagers;
  25. using Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.Logging;
  26. using Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.NetFramework.Logging;
  27. using Microsoft.Samples.NLayerApp.Infrastructure.Data.MainModule.Mock;
  28. using Microsoft.Samples.NLayerApp.Infrastructure.Data.MainModule.Repositories;
  29. using Microsoft.Samples.NLayerApp.Infrastructure.Data.MainModule.UnitOfWork;
  30. //(CDLTLL) Added for Calls Interception Example
  31. using Microsoft.Practices.Unity.InterceptionExtension;
  32. using System.Diagnostics;
  33. using Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.Unity.InterceptionBehaviors;
  34. namespace Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.Unity
  35. {
  36. /// <summary>
  37. /// Implemented container in Microsoft Practices Unity
  38. /// </summary>
  39. sealed class IoCUnityContainer
  40. :IContainer
  41. {
  42. #region Members
  43. IDictionary<string, IUnityContainer> _ContainersDictionary;
  44. #endregion
  45. #region Constructor
  46. /// <summary>
  47. /// Create a new instance of IoCUnitContainer
  48. /// </summary>
  49. public IoCUnityContainer()
  50. {
  51. _ContainersDictionary = new Dictionary<string, IUnityContainer>();
  52. //Create root container
  53. IUnityContainer rootContainer = new UnityContainer();
  54. rootContainer.AddNewExtension<Interception>();
  55. _ContainersDictionary.Add("RootContext", rootContainer);
  56. //Create container for real context, child of root container
  57. IUnityContainer realAppContainer = rootContainer.CreateChildContainer();
  58. _ContainersDictionary.Add("RealAppContext", realAppContainer);
  59. //Create container for testing, child of root container
  60. IUnityContainer fakeAppContainer = rootContainer.CreateChildContainer();
  61. _ContainersDictionary.Add("FakeAppContext", fakeAppContainer);
  62. ConfigureRootContainer(rootContainer);
  63. ConfigureRealContainer(realAppContainer);
  64. ConfigureFakeContainer(fakeAppContainer);
  65. }
  66. #endregion
  67. #region Private Methods
  68. /// <summary>
  69. /// Configure root container.Register types and life time managers for unity builder process
  70. /// </summary>
  71. /// <param name="container">Container to configure</param>
  72. void ConfigureRootContainer(IUnityContainer container)
  73. {
  74. // Take into account that Types and Mappings registration could be also done using the UNITY XML configuration
  75. //But we prefer doing it here (C# code) because we'll catch errors at compiling time instead execution time,
  76. //if any type has been written wrong.
  77. //Register Repositories mappings
  78. container.RegisterType<IProductRepository, ProductRepository>(new TransientLifetimeManager());
  79. container.RegisterType<IOrderRepository, OrderRepository>(new TransientLifetimeManager());
  80. container.RegisterType<IBankAccountRepository, BankAccountRepository>(new TransientLifetimeManager());
  81. container.RegisterType<ICustomerRepository, CustomerRepository>(new TransientLifetimeManager());
  82. container.RegisterType<ICountryRepository, CountryRepository>(new TransientLifetimeManager());
  83. //Register application services mappings
  84. container.RegisterType<ISalesManagementService, SalesManagementService>(new TransientLifetimeManager());
  85. container.RegisterType<ICustomerManagementService, CustomerManagementService>(new TransientLifetimeManager());
  86. container.RegisterType<IBankingManagementService, BankingManagementService>(new TransientLifetimeManager());
  87. //Register domain services mappings
  88. //(CDLTLL) Just Mapping with no Calls-Interception
  89. //container.RegisterType<IBankTransferDomainService, BankTransferDomainService>(new TransientLifetimeManager());
  90. //(CDLTLL) Extending with Calls Interception
  91. container.RegisterType<IBankTransferDomainService, BankTransferDomainService>(new TransientLifetimeManager(),
  92. new Interceptor<InterfaceInterceptor>(),
  93. new InterceptionBehavior(new AuditBehavior(new TraceSource("interception-audit-source"))));
  94. //Register crosscuting mappings
  95. container.RegisterType<ITraceManager, TraceManager>(new TransientLifetimeManager());
  96. }
  97. /// <summary>
  98. /// Configure real container. Register types and life time managers for unity builder process
  99. /// </summary>
  100. /// <param name="container">Container to configure</param>
  101. void ConfigureRealContainer(IUnityContainer container)
  102. {
  103. container.RegisterType<IMainModuleUnitOfWork, MainModuleUnitOfWork>(new PerResolveLifetimeManager(),new InjectionConstructor());
  104. }
  105. /// <summary>
  106. /// Configure fake container.Register types and life time managers for unity builder process
  107. /// </summary>
  108. /// <param name="container">Container to configure</param>
  109. void ConfigureFakeContainer(IUnityContainer container)
  110. {
  111. //Note: Generic register type method cannot be used here,
  112. //MainModuleFakeContext cannot have implicit conversion to IMainModuleContext
  113. container.RegisterType(typeof(IMainModuleUnitOfWork), typeof(FakeMainModuleUnitOfWork), new PerResolveLifetimeManager());
  114. }
  115. #endregion
  116. #region IServiceFactory Members
  117. /// <summary>
  118. /// <see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.IContainer.Resolve{TService}"/>
  119. /// </summary>
  120. /// <typeparam name="TService"><see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.IContainer.Resolve{TService}"/></typeparam>
  121. /// <returns><see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.IContainer.Resolve{TService}"/></returns>
  122. public TService Resolve<TService>()
  123. {
  124. //We use the default container specified in AppSettings
  125. string containerName = ConfigurationManager.AppSettings["defaultIoCContainer"];
  126. if (String.IsNullOrEmpty(containerName)
  127. ||
  128. String.IsNullOrWhiteSpace(containerName))
  129. {
  130. throw new ArgumentNullException(Messages.exception_DefaultIOCSettings);
  131. }
  132. if (!_ContainersDictionary.ContainsKey(containerName))
  133. throw new InvalidOperationException(Messages.exception_ContainerNotFound);
  134. IUnityContainer container = _ContainersDictionary[containerName];
  135. return container.Resolve<TService>();
  136. }
  137. /// <summary>
  138. /// <see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.IContainer.Resolve"/>
  139. /// </summary>
  140. /// <param name="type"><see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.IContainer.Resolve"/></param>
  141. /// <returns><see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.IContainer.Resolve"/></returns>
  142. public object Resolve(Type type)
  143. {
  144. //We use the default container specified in AppSettings
  145. string containerName = ConfigurationManager.AppSettings["defaultIoCContainer"];
  146. if (String.IsNullOrEmpty(containerName)
  147. ||
  148. String.IsNullOrWhiteSpace(containerName))
  149. {
  150. throw new ArgumentNullException(Messages.exception_DefaultIOCSettings);
  151. }
  152. if (!_ContainersDictionary.ContainsKey(containerName))
  153. throw new InvalidOperationException(Messages.exception_ContainerNotFound);
  154. IUnityContainer container = _ContainersDictionary[containerName];
  155. return container.Resolve(type, null);
  156. }
  157. /// <summary>
  158. /// <see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.IContainer.RegisterType"/>
  159. /// </summary>
  160. /// <param name="type"><see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.IoC.IContainer.RegisterType"/></param>
  161. public void RegisterType(Type type)
  162. {
  163. IUnityContainer container = this._ContainersDictionary["RootContext"];
  164. if (container != null)
  165. container.RegisterType(type, new TransientLifetimeManager());
  166. }
  167. #endregion
  168. }
  169. }