private static void Main(string[] args) { if (args.Length == 0) { args = new[] { "10", "+", "20", "+", "30" }; } using (var container = new UnityContainer()) { Bootstrapper.SetupContainer(container); using (var childContainer = container.CreateChildContainer()) { Bootstrapper.SetupChildContainer(childContainer); PerformCalculationAndWriteResult(args, childContainer); } using (var childContainer = container.CreateChildContainer()) { Bootstrapper.SetupChildContainer(childContainer); PerformCalculationAndWriteResult(args, childContainer); } } }
public void Test() { var container = new UnityContainer(); container.RegisterDatabase<MockDbContext>() .RegisterRepository(x => x.MockEntity1s) .RegisterRepository(x => x.MockEntity2s); var resolve1 = container.CreateChildContainer().Resolve<ResolveTree>(); Assert.AreSame(resolve1.DbContext, resolve1.Repo1.DbContext); Assert.AreSame(resolve1.DbContext, resolve1.Repo2.DbContext); var resolve2 = container.CreateChildContainer().Resolve<ResolveTree>(); Assert.AreNotSame(resolve1.DbContext, resolve2.DbContext); }
private static void Main(string[] args) { if (args.Length == 0) { args = new[] { "10", "+", "20", "+", "30", "-", "12" }; } using (var container = new UnityContainer()) { Bootstrapper.SetupContainer(container); try { PerformCalculation(args, container); } catch (Exception exception) { // Since the Minus class is registered only in the child container // the default expression cannot be evaluated on the root container Console.WriteLine(exception); } using (var childContainer = container.CreateChildContainer()) { Bootstrapper.SetupChildContainer(childContainer); PerformCalculation(args, childContainer); } } }
public CollectService() { var diContainer = new UnityContainer().CreateChildContainer(); lock (ScheduleInitLock) { var scheduler = new Quartz.Impl.StdSchedulerFactory().GetScheduler(); if (ScheduleController == null) { SchedulerContainer = diContainer.CreateChildContainer(); scheduler.JobFactory = new UnityJobFactory(SchedulerContainer); ScheduleController = new ScheduleController(scheduler); ScheduleController.ReschedulingAlreadyExecuted = false; } diContainer.RegisterType<IDataProvider, DataProvider>(new ContainerControlledLifetimeManager()); diContainer.RegisterType<ICollectRequestRepository, CollectRequestRepository>(new ContainerControlledLifetimeManager()); diContainer.RegisterType<IProbeManager, ProbeManager>(); diContainer.RegisterType<ICollectRequestAssembler, CollectRequestAssembler>(new ContainerControlledLifetimeManager()); diContainer.RegisterType<ICollectPackageAssembler, CollectPackageAssembler>(new ContainerControlledLifetimeManager()); diContainer.RegisterType<ICollectResultAssembler, CollectResultAssembler>(new ContainerControlledLifetimeManager()); diContainer.RegisterType<IDefinitionDocumentFactory, DefinitionDocumentFactory>(new ContainerControlledLifetimeManager()); diContainer.RegisterInstance<IScheduler>(scheduler); diContainer.RegisterInstance<IScheduleController>(ScheduleController); CollectController = diContainer.Resolve<CollectController>(); } }
public static IUnityContainer CreateContainer() { IUnityContainer parentContaier = new UnityContainer(); IUnityContainer orderContainer = parentContaier.CreateChildContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(orderContainer, "containerOne"); return orderContainer; }
public void CheckParentContOfParent() { UnityContainer uc = new UnityContainer(); IUnityContainer ucchild = uc.CreateChildContainer(); object obj = uc.Parent; Assert.IsNull(obj); }
public void CheckParentContOfChild() { UnityContainer uc = new UnityContainer(); IUnityContainer ucchild = uc.CreateChildContainer(); object obj = ucchild.Parent; Assert.AreSame(uc, obj); }
public void WhenResolveingAnIUnityContainerForAChildContainerItResolvesTheChildContainer() { IUnityContainer container = new UnityContainer(); IUnityContainer childContainer = container.CreateChildContainer(); IUnityContainer resolvedContainer = childContainer.Resolve<IUnityContainer>(); Assert.AreSame(childContainer, resolvedContainer); }
public void ChildContainerResolvesSelf() { var container = new UnityContainer(); var child = container.CreateChildContainer(); var candidate = child.Resolve<IUnityContainer>(); Assert.AreSame(child, candidate); }
public void NamesRegisteredInParentAppearInChild() { UnityContainer parent = new UnityContainer(); parent.RegisterType<ITemporary, SpecialTemp>("test"); IUnityContainer child = parent.CreateChildContainer(); ITemporary temp = child.Resolve<ITemporary>("test"); Assert.IsInstanceOfType(temp, typeof(SpecialTemp)); }
public void ChildInheritsParentsConfiguration_RegisterTypeResolve() { UnityContainer parent = new UnityContainer(); parent.RegisterType<ITestContainer, TestContainer>(new ContainerControlledLifetimeManager()); IUnityContainer child = parent.CreateChildContainer(); ITestContainer objtest = child.Resolve<ITestContainer>(); Assert.IsNotNull(objtest); Assert.IsInstanceOfType(objtest, typeof(TestContainer)); }
public void DisposingParentDisposesChild() { UnityContainer parent = new UnityContainer(); IUnityContainer child = parent.CreateChildContainer(); MyDisposableObject spy = new MyDisposableObject(); child.RegisterInstance(spy); parent.Dispose(); Assert.IsTrue(spy.WasDisposed); }
public void CreateChildUsingParentsConfiguration() { UnityContainer parent = new UnityContainer(); parent.RegisterType<ITemporary, Temporary>(); IUnityContainer child = parent.CreateChildContainer(); ITemporary temp = child.Resolve<ITemporary>(); Assert.IsNotNull(temp); Assert.IsInstanceOfType(temp, typeof(Temporary)); }
public void ChildContainerResolvesInParentDefault() { var container = new UnityContainer(); var child = container.CreateChildContainer(); container.RegisterInstance("test", child); var candidate = container.Resolve<IUnityContainer>("test"); Assert.AreSame(child, candidate); }
public void Test() { IUnityContainer container = new UnityContainer(); container.RegisterType<MyObject>(new ContainerControlledLifetimeManager()); IUnityContainer childContainer = container.CreateChildContainer(); var a1 = childContainer.Resolve<MyObject>(); var a2 = container.Resolve<MyObject>(); Assert.AreSame(a1, a2); }
public void OptionalParametersResolvedIfInstanceRegisteredInParentWithName() { IUnityContainer parent = new UnityContainer(); IUnityContainer child = parent.CreateChildContainer(); var input = new TestObject(); parent.RegisterInstance<ITestObject>("test", input); NamedOptionalConstParameterClass result = child.Resolve<NamedOptionalConstParameterClass>(); Assert.AreSame(input, result.TestObject); }
public void NamesRegisteredInParentAppearInChildGetAll() { string[] numbers = { "first", "second", "third" }; UnityContainer parent = new UnityContainer(); parent.RegisterInstance(numbers[0], "first") .RegisterInstance(numbers[1], "second"); IUnityContainer child = parent.CreateChildContainer() .RegisterInstance(numbers[2], "third"); List<string> nums = new List<string>(child.ResolveAll<string>()); CollectionAssert.AreEquivalent(numbers, nums); }
/// <summary> /// Inicializa el contenedor. /// </summary> public static void Initialize() { var containersDictionary = new Dictionary<string, IUnityContainer>(); // Creamos los contenedores var rootContainer = new UnityContainer(); var realAppContainer = rootContainer.CreateChildContainer(); var fakeAppContainer = rootContainer.CreateChildContainer(); // Los añadimos al diccionario containersDictionary.Add("RootContext", rootContainer); containersDictionary.Add("RealAppContext", realAppContainer); containersDictionary.Add("FakeAppContext", fakeAppContainer); // Configuramos los contenedores rootContainer.AddNewExtension<CommonTypesExtension>(); realAppContainer.AddNewExtension<RealTypesExtension>(); fakeAppContainer.AddNewExtension<FakeTypesExtension>(); // Definimos el contenedor en el ServiceLocator ServiceLocator.SetLocatorProvider(() => new CustomUnityServiceLocator(containersDictionary)); }
public void ChildInheritsParentsConfiguration_RegisterInstanceResolve() { UnityContainer parent = new UnityContainer(); ITestContainer obj = new TestContainer(); parent.RegisterInstance<ITestContainer>("InParent", obj); IUnityContainer child = parent.CreateChildContainer(); ITestContainer objtest = child.Resolve<ITestContainer>("InParent"); Assert.IsNotNull(objtest); Assert.AreSame(objtest, obj); }
public void ChildConfigurationOverridesParentConfiguration() { UnityContainer parent = new UnityContainer(); parent.RegisterType<ITemporary, Temporary>(); IUnityContainer child = parent.CreateChildContainer() .RegisterType<ITemporary, SpecialTemp>(); ITemporary parentTemp = parent.Resolve<ITemporary>(); ITemporary childTemp = child.Resolve<ITemporary>(); Assert.IsInstanceOfType(parentTemp, typeof(Temporary)); Assert.IsInstanceOfType(childTemp, typeof(SpecialTemp)); }
public void Bug_4709_ParentAndChildResolveWithSameRegistered1() { UnityConfigurationSection section = ConfigurationFixtureBase.GetUnitySection(ConfigFileName); IUnityContainer root = new UnityContainer(); section.Configure(root); IUnityContainer child = root.CreateChildContainer(); section.Configure(child, "ModuleName"); ISomeInterface obj = child.Resolve<ISomeInterface>(); Assert.AreEqual<int>(3, obj.Count()); ISomeInterface obj1 = root.Resolve<ISomeInterface>(); Assert.AreEqual<int>(1, obj1.Count()); }
public void Test11() { var container = new UnityContainer(); container.RegisterType<RemoteService>(new ContainerControlledLifetimeManager()); container.RegisterType<IService, RemoteService>(); container.RegisterType<IService2, RemoteService>(); var childContainer = container.CreateChildContainer(); childContainer.RegisterType<RemoteService>(new PerResolveLifetimeManager()); var instance = childContainer.Resolve<IService>(); var instance2 = childContainer.Resolve<IService2>(); Assert.AreNotEqual(instance, instance2); Assert.IsInstanceOf<RemoteService>(instance); Assert.IsInstanceOf<RemoteService>(instance2); }
public static void RegisterComponents() { var container = new UnityContainer(); var connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Mongo"].ConnectionString; var database = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Mongo"].ProviderName; container.RegisterType<IMongoConnectionHandler, MongoConnectionHandler>( new ContainerControlledLifetimeManager(), new InjectionConstructor(connectionString, database)); var serviceBuilder = ExchangeConferenceRoomService.GetExchangeServiceBuilder( ConfigurationManager.AppSettings["username"], ConfigurationManager.AppSettings["password"], ConfigurationManager.AppSettings["serviceUrl"]); container.RegisterType<ExchangeService>(new HierarchicalLifetimeManager(), new InjectionFactory(c => serviceBuilder())); container.RegisterType<Func<ExchangeService>>(new HierarchicalLifetimeManager(), new InjectionFactory(c => serviceBuilder)); container.RegisterType<IBroadcastService, SignalrBroadcastService>(new HierarchicalLifetimeManager()); container.RegisterType<IConferenceRoomService, ExchangeConferenceRoomService>(new HierarchicalLifetimeManager()); container.RegisterType<IMeetingRepository, MeetingRepository>(new HierarchicalLifetimeManager()); container.RegisterType<ISecurityRepository, SecurityRepository>(new HierarchicalLifetimeManager()); container.RegisterType<IConnectionManager>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => GlobalHost.ConnectionManager)); container.RegisterType<IDateTimeService>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => new DateTimeService(TimeSpan.FromHours(0)))); container.RegisterType<IMeetingCacheService, MeetingCacheService>(new ContainerControlledLifetimeManager()); // singleton cache container.RegisterInstance(typeof(IConcurrencyLimiter), new ConcurrencyLimiter(int.Parse(ConfigurationManager.AppSettings["concurrencyLimit"] ?? "1")), new ContainerControlledLifetimeManager()); // create change notifier in a child container and register as a singleton with the main container (avoids creating it's dependencies in the global container) var child = container.CreateChildContainer(); var changeNotificationService = child.Resolve<ChangeNotificationService>(); container.RegisterInstance(typeof(IChangeNotificationService), changeNotificationService, new ContainerControlledLifetimeManager()); // register all your components with the container here // it is NOT necessary to register your controllers // e.g. container.RegisterType<ITestService, TestService>(); GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); }
public void ChildContainer_Test() { DisposableClass obj1, obj2; using (var container = new UnityContainer()) { container.AddNewExtension<DisposableStrategyExtension>(); container.RegisterType<DisposableClass>(new DisposingSharedLifetimeManager()); obj1 = container.Resolve<DisposableClass>(); using (IUnityContainer childContainer = container.CreateChildContainer()) { obj2 = childContainer.Resolve<DisposableClass>(); Assert.AreEqual(obj1, obj2); } Assert.IsFalse(obj2.Disposed); } Assert.IsTrue(obj1.Disposed); }
public static UnityContainer Initialize(string path, TerrificNetHostConfiguration configuration, ServerConfiguration serverConfiguration) { var container = new UnityContainer(); container.RegisterType<ITerrificTemplateHandler, DefaultTerrificTemplateHandler>(); container .RegisterType //<ITerrificTemplateHandlerFactory, GenericUnityTerrificTemplateHandlerFactory<DefaultTerrificTemplateHandler>>(); <ITerrificTemplateHandlerFactory, GenericUnityTerrificTemplateHandlerFactory<PageEditDefaultTerrificTemplateHandler>>(); container.RegisterType<INamingRule, NamingRule>(); container.RegisterInstance(serverConfiguration); new DefaultUnityModule().Configure(container); #if DEBUG var fileSystem = new FileSystem(path); container.RegisterInstance<IFileSystem>(fileSystem); #else container.RegisterInstance<IFileSystem>(new EmbeddedResourceFileSystem(typeof(WebInitializer).Assembly)); #endif foreach (var item in configuration.Applications.Values) { var childContainer = container.CreateChildContainer(); var app = DefaultUnityModule.RegisterForApplication(childContainer, path, item.BasePath, item.ApplicationName, item.Section); container.RegisterInstance(item.ApplicationName, app); } foreach (var app in container.ResolveAll<TerrificNetApplication>()) { foreach (var template in app.Container.Resolve<ITemplateRepository>().GetAll()) { Console.WriteLine(template.Id); } } new TerrificBundleUnityModule().Configure(container); return container; }
public WebApiFixture() { var unity = new UnityContainer(); unity.ConfigureCms() .UseMemoryStorage() .UseLuceneSearch(new RAMDirectory()) .UseTextRenderer() .UseHtmlRenderer() .UseMarkdownRenderer() .UseSourceCodeRenderer(); Cms.Configure(() => new UnityCmsContainer(unity.CreateChildContainer())); using (var context = Cms.CreateContext()) { ExampleDocument = new CmsDocument("Example"); context.Documents.Save(ExampleDocument); ExampleView = new CmsView("Example"); context.Views.Save(ExampleView); } //CmsTesting.Initialize(() => new UnityCmsContainer(unity.CreateChildContainer())); _WebApp = WebApp.Start<Startup>(WebUrl.ToString()); }
public void ProblemDefinition() { using (IUnityContainer unityContainer = new UnityContainer()) { unityContainer.RegisterType<IService, BaseService>(); unityContainer.RegisterType<IService, FacadeService>("facade"); Enumerable.Range(0, 2).ForEach(i => { using (IUnityContainer childContainer = unityContainer.CreateChildContainer()) { childContainer.RegisterType<IService, BaseService>(new ContainerControlledLifetimeManager()); IService service = childContainer.Resolve<IService>("facade"); service.Foo(String.Format("problemDefinitionTest({0})", i)); Console.WriteLine("before childContainer.Dispose()"); } }); Console.WriteLine("before unityContainer.Dispose()"); } }
public void HierarchicalLifetimeManager_Child_Not_Equal_To_Parent() { // Create parent container IUnityContainer parentCtr = new UnityContainer(); // Register type in parent container parentCtr.RegisterType<MyObject>(new HierarchicalLifetimeManager()); // Create nested child container in parent container IUnityContainer childCtr = parentCtr.CreateChildContainer(); MyObject parentObject1 = parentCtr.Resolve<MyObject>(); MyObject parentObject2 = parentCtr.Resolve<MyObject>(); Assert.That(parentObject2.GetHashCode(), Is.EqualTo(parentObject1.GetHashCode()), "paren1 != parent2"); MyObject childObject = childCtr.Resolve<MyObject>(); Assert.That(childObject.GetHashCode(), Is.Not.EqualTo(parentObject1.GetHashCode()), "child != parent"); // Dispose child container childCtr.Dispose(); // Dispose parent container parentCtr.Dispose(); }
static void TestHierarchicalLifetime() { Console.WriteLine("Test HierarchicalLifetimeManager"); LifetimeTest.ResetCounter(); using (var parentContainer = new UnityContainer()) { var lifeManager = new ContainerControlledLifetimeManager(); // HierarchicalLifetimeManager(); parentContainer.RegisterType<ILifetimeTest, LifetimeTest>(lifeManager); // 建立子容器 var childContainer = parentContainer.CreateChildContainer(); var obj1 = parentContainer.Resolve<ILifetimeTest>(); // 使用父容器解析 var obj2 = childContainer.Resolve<ILifetimeTest>(); // 使用子容器解析 LifetimeTest.PrintCounter(); // 印出 ObjectCounter=2 } LifetimeTest.PrintCounter(); // 印出 ObjectCounter=0 }
public void NestedContainerOverrideInParentDoesNotReturnOverridenInChildAcrossCalls() { IToWhichDependent overrideValue = new Type2ToWhichDependent(222); IUnityContainer container = new UnityContainer(); IUnityContainer childContainer = container.CreateChildContainer(); // Registering the parent default types. container.RegisterType<IDependingOnOtherType, Type1DependingOnOtherType>().RegisterType<IToWhichDependent, Type1ToWhichDependent>(new InjectionConstructor(111)); // Overriding the default values for the parent container. Type1DependingOnOtherType parentResult = (Type1DependingOnOtherType)container.Resolve<IDependingOnOtherType>(new DependencyOverride(typeof(IToWhichDependent), overrideValue)); // Resolving child container to the default type. Type1DependingOnOtherType childResult = (Type1DependingOnOtherType)childContainer.Resolve<IDependingOnOtherType>(); // The parent overriden values should be reflected. Assert.IsInstanceOfType(parentResult.IToWhichDependent, typeof(Type2ToWhichDependent)); Assert.IsInstanceOfType(parentResult.OneMoreIToWhichDependent, typeof(Type2ToWhichDependent)); Assert.AreEqual<int>(parentResult.IToWhichDependent.X, 222); // The parent default registered type should be reflected, since there are no type registered exclusively for the child container. Assert.IsInstanceOfType(childResult.IToWhichDependent, typeof(Type1ToWhichDependent)); Assert.IsInstanceOfType(childResult.OneMoreIToWhichDependent, typeof(Type1ToWhichDependent)); Assert.AreEqual<int>(childResult.IToWhichDependent.X, 111); }