private object DoBuildUp(Type t, object existing, string name, InjectionMember[] injectionMembers)
        {
            var transientPolicies = new PolicyList(this.Context.Policies);
            foreach (var member in injectionMembers)
            {
                member.AddPolicies(null, t, name, transientPolicies);
            }

            object result;
            var buildContext = new BuilderContext(Context.Strategies.MakeStrategyChain(),
                Context.Lifetime, Context.Policies, transientPolicies, new NamedTypeBuildKey(t, name),
                existing);
            try
            {
                result = buildContext.Strategies.ExecuteBuildUp(buildContext);
            }
            catch (Exception exception)
            {
                throw new ResolutionFailedException(t, name, exception, buildContext);
            }
            return result;
        }
Пример #2
0
        /// <summary>
        /// Loads the main job configuration.
        /// </summary>
        /// <param name="unityContainer">The container to register to.</param>
        protected virtual void LoadConfiguration(IUnityContainer unityContainer)
        {
            if (PersistenceSupport)
            {
                var tablePrefix = ConfigurationManager.AppSettings[AbstractDbBatchMetadataDao.TablePrefixSetting];
                var injectionMembers = new InjectionMember[tablePrefix == null ? 1 : 2];
                injectionMembers[0] = new InjectionProperty("ConnectionStringSettings",
                    new ResolvedParameter<ConnectionStringSettings>("Default"));
                if (tablePrefix != null)
                {
                    injectionMembers[1] = new InjectionProperty("TablePrefix", tablePrefix);
                }

                unityContainer.RegisterSingletonWithFactory<IJobRepository, DbJobRepositoryFactory>(injectionMembers);
                unityContainer.RegisterSingletonWithFactory<IJobExplorer, DbJobExplorerFactory>(injectionMembers);
            }
            else
            {
                unityContainer.RegisterSingletonWithFactory<IJobRepository, MapJobRepositoryFactory>();
                unityContainer.RegisterSingletonWithFactory<IJobExplorer, MapJobExplorerFactory>();

            }
            unityContainer.RegisterSingleton<IJobOperator, SimpleJobOperator>(new InjectionProperty("JobLauncher"),
                                                                        new InjectionProperty("JobRepository"),
                                                                        new InjectionProperty("JobExplorer"),
                                                                        new InjectionProperty("JobRegistry"));
            unityContainer.RegisterSingleton<IJobLauncher, SimpleJobLauncher>(new InjectionProperty("JobRepository"));
            unityContainer.RegisterSingleton<IListableJobLocator, MapJobRegistry>();

            unityContainer.RegisterSingleton<IJobParametersIncrementer, RunIdIncrementer>();

            unityContainer.RegisterSingleton<ITaskExecutor, SimpleAsyncTaskExecutor>();
        }
Пример #3
0
        /// <summary>
        /// RegisterType a type mapping with the container, where the created instances will use
        /// the given <see cref="LifetimeManager"/>.
        /// </summary>
        /// <param name="from"><see cref="Type"/> that will be requested.</param>
        /// <param name="to"><see cref="Type"/> that will actually be returned.</param>
        /// <param name="name">Name to use for registration, null if a default registration.</param>
        /// <param name="lifetimeManager">The <see cref="LifetimeManager"/> that controls the lifetime
        /// of the returned instance.</param>
        /// <param name="injectionMembers">Injection configuration objects.</param>
        /// <returns>The <see cref="UnityContainer"/> object that this method was called on (this in C#, Me in Visual Basic).</returns>
        public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, InjectionMember[] injectionMembers)
        {
            Guard.ArgumentNotNull(to, "to");
            if(string.IsNullOrEmpty(name))
            {
                name = null;
            }

            if (from != null && !from.IsGenericType && !to.IsGenericType)
            {
                Guard.TypeIsAssignable(from, to, "from");
            }

            registering(this, new RegisterEventArgs(from, to, name, lifetimeManager));

            if (injectionMembers.Length > 0)
            {
                ClearExistingBuildPlan(to, name);
                foreach(var member in injectionMembers)
                {
                    member.AddPolicies(from, to, name, policies);
                }
            }
            return this;
        }
Пример #4
0
 public IUnityContainer RegisterType(Type from, Type to, string name, LifetimeManager lifetimeManager, InjectionMember[] injectionMembers);
Пример #5
0
        private void Initialize(System.Web.HttpContext ctx)
        {
            m_Host = ctx.Request.Url.Host;
            var contextBase = new System.Web.HttpContextWrapper(ctx);

            var container = new UnityContainer();

            container.AddNewExtension<Interception>();

            // Enregistrement des repositories
            container.RegisterType<Repositories.ICouponRepository, Repositories.NullCouponRepository>(new ContainerControlledLifetimeManager());
            container.RegisterType<Repositories.ICartRepository, Repositories.HttpContextCartRepository>(new ContainerControlledLifetimeManager());
            container.RegisterType<Repositories.IRegistrationRepository, Repositories.SessionRegistrationRepository>(new ContainerControlledLifetimeManager());
            container.RegisterType<Repositories.ILocalizationRepository, Repositories.VoidLocalizationRepository>(new ContainerControlledLifetimeManager());
            container.RegisterType<Repositories.ICommentRepository, Repositories.VoidCommentRepository>(new ContainerControlledLifetimeManager());

            // Enregistrement des services
            container.RegisterType<Services.ICacheService, Services.SimpleCacheService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.ICartService, Services.CartService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.IScheduledTaskService, Services.ScheduledTaskService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.IEmailerService, Services.EmailerService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.IIncentiveService, Services.IncentiveService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.ILocalizationService, Services.VoidLocalizationService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.ISearchOptimizationService, Services.VoidSearchOptimizationService>(new ContainerControlledLifetimeManager());
            var pluginEnumeratorInjectionMembers = new InjectionMember[]
            {
                new InjectionConstructor(
                        ctx.Server.MapPath("/plugins.config")
                        , ctx.Server.MapPath("/bin")
                )
            };
            container.RegisterType<Extensibility.IPluginEnumerator, Extensibility.XmlConfigPluginEnumerator>(new ContainerControlledLifetimeManager(), pluginEnumeratorInjectionMembers);
            container.RegisterType<Extensibility.IPluginLoaderService, Extensibility.PluginLoaderService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.IEventSubscriptionService, Services.EventSubscriptionService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.IEventPublisher, Services.EventPublisher>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.ISettingsService, Services.SettingsService>(new ContainerControlledLifetimeManager());
            container.RegisterType<Services.ISalesService, Services.SalesService>(new ContainerControlledLifetimeManager());
            // Configuration des routes
            container.RegisterType<Services.IRoutesRegistrationService, ERPStoreRoutes>(new ContainerControlledLifetimeManager());

            // Enregistrement des modes de reglement par defaut
            container.RegisterType<Services.IPaymentService, Services.PaymentByCheckService>("check",new ContainerControlledLifetimeManager());
            container.RegisterType<Services.IPaymentService, Services.PaymentByWireTransferService>("wiretransfer",new ContainerControlledLifetimeManager());

            // Global Event Consumer
            container.RegisterType<Services.UserLoggedEventMessage>("userLoggedEventMessage", new ContainerControlledLifetimeManager());

            // Logger par defaut
            container.RegisterType<Logging.ILogger, Logging.ConsoleLogger>(new PerThreadLifetimeManager());

            // Chargement des services et overriding a partir du fichier
            // de configuration unity.config
            var map = new ExeConfigurationFileMap();
            var unityConfigFileName = ERPStore.Configuration.ConfigurationSettings.AppSettings["unityConfigFileName"] ?? "unity.config";
            map.ExeConfigFilename = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath(@"\"), unityConfigFileName);
            var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            var section = (UnityConfigurationSection)config.GetSection("unity");
            if (section == null)
            {
                throw new Exception(string.Format("unity section in {0} does not exists", unityConfigFileName));
            }
            section.Configure(container);

            RegisterGlobalFilters(GlobalFilters.Filters);

            container.RegisterInstance<IControllerFactory>(System.Web.Mvc.ControllerBuilder.Current.GetControllerFactory());
            container.RegisterType<IControllerActivator, UnityControllerActivator>();
            container.RegisterType<IViewPageActivator, UnityViewPageActivator>();
            var filterProvider = new UnityFilterProvider(container);
            container.RegisterInstance<IFilterProvider>("attributes", filterProvider);
            container.RegisterType<ModelMetadataProvider, DataAnnotationsModelMetadataProvider>();
            var resolver = new UnityDependencyResolver(container);
            System.Web.Mvc.DependencyResolver.SetResolver(resolver);

            m_Logger = container.Resolve<Logging.ILogger>();

            // Resolution et chargement des paramètres de configuration du site
            m_Logger.Info("Loading site configuration");
            var settingsService = container.Resolve<Services.ISettingsService>();
            m_WebSiteSettings = settingsService.GetWebSiteSettings(m_Host);
            m_WebSiteSettings.PhysicalPath = ctx.Server.MapPath("/");

            var injectionMembers = new InjectionMember[]
            {
                new InjectionConstructor(m_WebSiteSettings.CryptoKey, m_WebSiteSettings.CryptoIV) ,
            };
            container.RegisterType<Services.CryptoService>(new ContainerControlledLifetimeManager(), injectionMembers);

            m_Logger.Info("Loading plugins");
            // Chargement des plugins
            var pluginLoaderService = container.Resolve<Extensibility.IPluginLoaderService>();
            var pluginEnumeratorService = container.Resolve<Extensibility.IPluginEnumerator>();
            var plugins = pluginEnumeratorService.EnumeratePlugins();
            pluginLoaderService.Load(plugins, (System.Web.HttpContextBase)contextBase, m_WebSiteSettings);
            m_Logger.Info("Plugins loaded");

            // Configuration des routes
            var erpStoreRoutes = container.Resolve<Services.IRoutesRegistrationService>();
            erpStoreRoutes.Register();

            // Enregistrement des routes par defaut

            RouteTable.Routes.MapERPStoreRoute(
                "Admin"
                , "admin/{action}/{id}"
                , new { controller = "Admin", action = "Index", id = string.Empty }
            );

            RouteTable.Routes.MapERPStoreRoute(
                "CatchAll"
                , "{*catchall}"
                , new { controller = "Home", action = "CatchAll" }
            );

            // Ne pas supprimer cette route
            RouteTable.Routes.MapERPStoreRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = string.Empty }
            );

            var eventPublisherService = container.Resolve<Services.IEventPublisher>();
            eventPublisherService.Publish(new Models.Events.RegisteredRoutesEvent());

            m_Logger.Info("Routes configured");

            // Demarrage du planificateur de taches
            var taskService = container.Resolve<Services.IScheduledTaskService>();
            taskService.Start();
            m_Logger.Info("Scheduler started");
        }
Пример #6
0
 private static InjectionMember[] GetInjectionMembersAndLogging(InjectionMember[] injectionMembers)
 {
     foreach (var injectionMember in injectionMembers)
     {
         if (injectionMember.GetType() == typeof (Interceptor<>) &&
             injectionMember.GetType().GenericTypeArguments.Length > 0 &&
             injectionMember.GetType().GenericTypeArguments[0] == typeof (InterfaceInterceptor))
         {
             var allInjectionMembersPreExistingInteceptor =
                 new InjectionMember[]
                 {
                     new InterceptionBehavior<LoggingInterceptor>()
                 }.Concat(
                     injectionMembers).ToArray();
             return allInjectionMembersPreExistingInteceptor;
         }
     }
     var allInjectionMembers =
         new InjectionMember[]
         {
             new Interceptor<InterfaceInterceptor>(),
             new InterceptionBehavior<LoggingInterceptor>()
         }.Concat(
             injectionMembers).ToArray();
     return allInjectionMembers;
 }
		private static void AssertHasInjectionMembers(InjectionMember[] members)
		{
			Assert.IsInstanceOfType(members.First(), typeof(Interceptor<InterfaceInterceptor>));
			Assert.IsInstanceOfType(members.Last(), typeof(InterceptionBehavior<PolicyInjectionBehavior>));
			Assert.AreEqual(2, members.Count());
		}
		public void PerformRegistrations_CreatesAllParts_RegistersItIntoUnity()
		{
			var lifetimeManager = new ContainerControlledLifetimeManager();
			var injectionMembers = new InjectionMember[] { new InterceptionBehavior<PolicyInjectionBehavior>() };

			StubCreateInjectionMembers(injectionMembers);
			registrationNameFactory.Setup(f => f.GetRegistrationName(It.IsAny<TypeMapping>())).Returns("TEST");
			configLifetimeManagerFactory.Setup(l => l.CreateLifetimeManager(It.IsAny<TypeMapping>())).Returns(lifetimeManager);

			// Act
			handler.PerformRegistrations(target.Object, new[] { new TypeMapping(typeof(String), typeof(Boolean)) });

			// Assert
			target.Verify(t => t.RegisterType(typeof(String), typeof(Boolean), "TEST", lifetimeManager, injectionMembers));
		}
Пример #9
0
        private void EnsurePluginClassesExist()
        {
            if (pluginClasses.Count == pluginTypes.Count)
            {
                return;
            }

            foreach (Type pluginType in pluginTypes)
            {
                var pluginEnumeratorInjectionMembers = new InjectionMember[]
                {
                    new InjectionConstructor(
                            m_Container
                            , m_HttpContext
                            , m_WebSiteSettings
                    )
                };
                m_Container.RegisterType(pluginType, new ContainerControlledLifetimeManager(), pluginEnumeratorInjectionMembers);
                var plugin = m_Container.Resolve(pluginType) as PluginInit;
                pluginClasses.Add(plugin);
            }
        }