/// <summary> /// Register dependencies of current project /// </summary> public static void Register() { using (var containerControlledLifetimeManager = new ContainerControlledLifetimeManager()) { DIContainer.Instance.RegisterType<IApplicationSetting, ApplicationSetting>(containerControlledLifetimeManager); } }
public LifetimeManager CreateLifeTimeManager(LifeTimeManagerType type) { LifetimeManager result = null; switch (type) { case LifeTimeManagerType.ContainerControlled: result = new ContainerControlledLifetimeManager(); break; case LifeTimeManagerType.HierarchicalLifetime: result = new HierarchicalLifetimeManager(); break; case LifeTimeManagerType.PerResolveLifetime: result = new PerResolveLifetimeManager(); break; case LifeTimeManagerType.ExternallyControlledLifetime: result = new ExternallyControlledLifetimeManager(); break; case LifeTimeManagerType.PerThreadLifetime: result = new PerThreadLifetimeManager(); break; case LifeTimeManagerType.TransientLifetime: result = new TransientLifetimeManager(); break; } return result; }
/// <summary> /// Checks if the instance being resolved has a lifetime manager. If it does not, an instance of /// <see cref="ContainerControlledLifetimeManager"/> is registered, which will then be used by /// <see cref="LifetimeStrategy"/>. /// </summary> /// <param name="context">Context of the build operation.</param> public override void PreBuildUp(IBuilderContext context) { if (context.Existing == null && !HasLifetimeManager(context)) { ILifetimePolicy lifetimeManager = new ContainerControlledLifetimeManager(); context.PersistentPolicies.Set(lifetimeManager, context.BuildKey); } }
public override void RegisterInstance(Type type, string name, object instance) { var lifetime = new ContainerControlledLifetimeManager(); if(string.IsNullOrEmpty(name)) { _container.RegisterInstance(type, instance, lifetime); } else { _container.RegisterInstance(type, name, instance, lifetime); } }
private static void ConfigureContainerAndUow() { var repositoryContainer = new UnityContainer(); repositoryContainer.RegisterType<ExpenseRepository, ExpenseRepository>(); var lifetimeManager = new ContainerControlledLifetimeManager(); repositoryContainer.RegisterType<IRepositoryStrategy, EntityFrameworkRepositoryStrategy>("ExpenseDatabase", lifetimeManager); UnitOfWork.SetRepositoryContainer(repositoryContainer); }
protected override void Context() { IUnityContainer repositoryContainer = UnitOfWork.GetRepositoryContainer(); repositoryContainer.RegisterInstance<INHibernateConfig>(NHibernateConfig.Create() .ServerIs(@"LUBU\SQLExpress2") .DatabaseNameIs("GreekFireExpenseTestDB")); repositoryContainer.RegisterType<ExpenseRepository, ExpenseRepository>(); var lifetimeManager = new ContainerControlledLifetimeManager(); repositoryContainer.RegisterType<IRepositoryStrategy, NHibernateRepositoryStrategy>("ExpenseDatabase", lifetimeManager); }
static void TestContainerControlledLifetime() { Console.WriteLine("Test ContainerControlledLifetimeManager"); LifetimeTest.ResetCounter(); using (var container = new UnityContainer()) { var lifeManager = new ContainerControlledLifetimeManager(); container.RegisterType<ILifetimeTest, LifetimeTest>(lifeManager); var obj1 = container.Resolve<ILifetimeTest>(); var obj2 = container.Resolve<ILifetimeTest>(); LifetimeTest.PrintCounter(); } LifetimeTest.PrintCounter(); }
public static void Build() { if (!_configured) { IUnityContainer repositoryContainer = UnitOfWork.GetRepositoryContainer(); repositoryContainer.RegisterType<ExpenseRepository, ExpenseRepository>(); var lifetimeManager = new ContainerControlledLifetimeManager(); repositoryContainer.RegisterType<IRepositoryStrategy, NHibernateRepositoryStrategy>("ExpenseDatabase", lifetimeManager); _configured = true; } }
/// <summary> /// Register dependencies of current project /// </summary> public static void Register() { DataAccess.Dependencies.Register(); DIContainer.Instance.RegisterType<IAuthenticateManager, AuthenticateManager>(); DIContainer.Instance.RegisterType<IAlertManager, AlertManager>(); DIContainer.Instance.RegisterType<IPersonManager, PersonManager>(); DIContainer.Instance.RegisterType<IMasterDataManager, MasterDataManager>(); DIContainer.Instance.RegisterType<IDashboardManager, DashboardManager>(); DIContainer.Instance.RegisterType<IVisitorManager, VisitorManager>(); DIContainer.Instance.RegisterType<IReportManager, ReportManager>(); RegisterFurtherRepository(); using (var containerControlledLifetimeManager = new ContainerControlledLifetimeManager()) { DIContainer.Instance.RegisterType<IComponentSettingsEntities, ComponentSettingsEntities>(containerControlledLifetimeManager); } }
LifetimeManager GetLifetimeManager(Type lifeTimeType) { LifetimeManager lifetimeManager; if (KnownTypes.SingleInstanceType.IsAssignableFrom(lifeTimeType)) { lifetimeManager = new ContainerControlledLifetimeManager(); } else if (KnownTypes.PerRequestType.IsAssignableFrom(lifeTimeType)) { lifetimeManager = new PerRequestLifetimeManager(); } else { lifetimeManager = new PerResolveLifetimeManager(); } return lifetimeManager; }
public void Initialize() { ConfigureRegionManager(_container); var singleton = new ContainerControlledLifetimeManager(); _container.RegisterType<IModule, PropertyInvestmentModule>(); _container.RegisterType<IRentalPropertyInputPresenter, RentalPropertyInputPresenter>(); _container.RegisterType<Repository.IDailyCompoundedMortgageRepository, Repository.DailyCompoundedMortgageRepository>(singleton); this.LoadViews(); var chartsPresenter = _container.Resolve<UI.Charts.ChartsPresenter>(); chartsPresenter.Show(); var inputControler = _container.Resolve<RentalPropertyController>(); inputControler.Show(); var inputControler2 = _container.Resolve<RentalPropertyController>(); inputControler2.Show(); }
public static void Register(this IUnityContainer container, IServiceDescriptor serviceDescriptor) { LifetimeManager lifetimeManager = null; switch (serviceDescriptor.Lifecycle) { case LifecycleKind.Singleton: lifetimeManager = new ContainerControlledLifetimeManager(); break; case LifecycleKind.Scoped: lifetimeManager = new HierarchicalLifetimeManager(); break; case LifecycleKind.Transient: lifetimeManager = new TransientLifetimeManager(); break; } if (serviceDescriptor.ImplementationInstance != null) container.RegisterInstance(serviceDescriptor.ServiceType, serviceDescriptor.ImplementationInstance); else container.RegisterType(serviceDescriptor.ServiceType, serviceDescriptor.ImplementationType, lifetimeManager); }
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)); }
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 Register(Type serviceKey, Type serviceType, bool singleton) { if (ReferenceEquals(serviceKey, null)) { throw new ArgumentNullException("serviceKey", "The serviceKey must not be null"); } if (ReferenceEquals(serviceType, null)) { throw new ArgumentNullException("serviceType", "The serviceType must not be null"); } if (!serviceType.IsClass || serviceType.IsAbstract) { throw new ArgumentException("The serviceType must be a non-abstract class type", "serviceType"); } LifetimeManager lifetimeManager; if (singleton) { lifetimeManager = new ContainerControlledLifetimeManager(); } else { lifetimeManager = new PerResolveLifetimeManager(); } _container.RegisterType(serviceKey, serviceType, lifetimeManager); }
/// <summary> /// Registers the type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="implementationType">Type of the implementation.</param> /// <param name="lifetime">The lifetime of the service.</param> /// <returns></returns> public override IServiceRegistrar RegisterType(Type serviceType, Type implementationType, LifetimeType lifetime) { Invariant.IsNotNull(serviceType, "serviceType"); Invariant.IsNotNull(implementationType, "implementationType"); LifetimeManager lifeTimeManager; switch (lifetime) { case LifetimeType.PerRequest: lifeTimeManager = new PerRequestLifetimeManager(); break; case LifetimeType.Singleton: lifeTimeManager = new ContainerControlledLifetimeManager(); break; default: lifeTimeManager = new TransientLifetimeManager(); break; } if (Container.Registrations.Any(registration => registration.RegisteredType.Equals(serviceType))) { Container.RegisterType(serviceType, implementationType, implementationType.FullName, lifeTimeManager); } else { Container.RegisterType(serviceType, implementationType, lifeTimeManager); } return this; }
// DependencyFactory.RegisterDependency(ProjectType.Wcf, "MT.Complex"); public static void RegisterDependency(ProjectType projecttype, string projectname) { string DllPath = string.Empty; switch ( projecttype ) { case ProjectType.Web: DllPath = AppDomain.CurrentDomain.BaseDirectory + "\\bin\\" + projectname + ".dll"; break; case ProjectType.Winfom: case ProjectType.WPF: case ProjectType.Wcf: case ProjectType.Test: DllPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + projectname + ".dll"; break; } if ( DllPath == null || DllPath.Length == 0 ) { throw new Exception("无法解析项目DLL"); } var typeList = Assembly.LoadFrom(DllPath).GetTypes().Where(t => t.Namespace != null && t.Namespace.Contains("Realization") && t.IsInterface == false && t.IsAbstract == false); var LifetimeManagerRegisterlist = typeList.Where(t => { return t.GetInterfaces().Intersect(ILifetimeManagerRegisterList).Count() > 0; }); foreach ( var t in LifetimeManagerRegisterlist ) { var InterfaceList = t.GetInterfaces().Where(p => { return !ILifetimeManagerRegisterList.Contains(p) && p.GetCustomAttribute(typeof(ICO_AOPEnableAttribute), false) != null; }); LifetimeManager lifetimemanager = new TransientLifetimeManager(); var intertype = t.GetInterfaces().Intersect(ILifetimeManagerRegisterList).First(); switch ( intertype.Name ) { case "IContainerControlledLifetimeManagerRegister": lifetimemanager = new ContainerControlledLifetimeManager(); break; case "IHierarchicalLifetimeManagerRegister": lifetimemanager = new HierarchicalLifetimeManager(); break; case "IExternallyControlledLifetimeManagerRegister": lifetimemanager = new ExternallyControlledLifetimeManager(); break; case "IPerThreadLifetimeManagerRegister": lifetimemanager = new PerThreadLifetimeManager(); break; case "IPerResolveLifetimeManagerRegister": lifetimemanager = new PerResolveLifetimeManager(); break; } foreach ( var iType in InterfaceList ) { ICOConfigAttribute ds = (ICOConfigAttribute) t.GetCustomAttribute(typeof(ICOConfigAttribute), false); ICO_AOPEnableAttribute ia = (ICO_AOPEnableAttribute) iType.GetCustomAttribute(typeof(ICO_AOPEnableAttribute), false); if ( ia.AOPEnable ) { var generator = new DynamicProxyGenerator(t, iType); Type type = generator.GenerateType(); // Type type = typeof(TransientLifetimeManager); DependencyUnityContainer.Current.RegisterType(iType, type, ds.Description, lifetimemanager); } else { DependencyUnityContainer.Current.RegisterType(iType, t, ds.Description, lifetimemanager); } } } }
/// <summary> /// Registers all Singleton instances where there should only be one instance of the registered object /// </summary> /// <param name="ucontainer">Unit Container that these instances are registered with</param> private void RegisterSingletons(UnityContainer ucontainer) { //Instantiate the lifetime manager to track the singletons _controlledLifetimeManager = new ContainerControlledLifetimeManager(); ucontainer.RegisterType<IJobRepository, JobRepository>(_controlledLifetimeManager); }
public void ComplicatedRegistrationsWithChildContainerLifetimes2() { var container = new QuickInjectContainer(); container.AddBuildPlanVisitor(new TransientLifetimeRemovalBuildPlanVisitor()); var child = container.CreateChildContainer(); var correctInstanceForIFooResolutionFromChild = new Foo(); var correctInstanceForFooResolutionFromChild = new SuperFoo(); var preSetFooOnLifetime = new Foo(); SuperFoo fooResolvedFromMainContainer = new SuperFoo(); var lifetime = new ContainerControlledLifetimeManager(); lifetime.SetValue(fooResolvedFromMainContainer); container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager(), new Microsoft.Practices.Unity.InjectionFactory(c => new Foo())); container.RegisterType<IBar, Foo>(new ContainerControlledLifetimeManager(), new Microsoft.Practices.Unity.InjectionFactory(c => correctInstanceForIFooResolutionFromChild)); container.RegisterType<Foo, SuperFoo>(new ContainerControlledLifetimeManager(), new Microsoft.Practices.Unity.InjectionFactory(c => fooResolvedFromMainContainer)); container.RegisterType<SuperFoo>(lifetime); child.RegisterType<Foo, SuperFoo>(new ContainerControlledLifetimeManager(), new Microsoft.Practices.Unity.InjectionFactory(c => correctInstanceForFooResolutionFromChild)); var f = container.Resolve<Foo>(); var g = container.Resolve<Foo>(); Assert.AreSame(child.Resolve<IBar>(), correctInstanceForIFooResolutionFromChild); Assert.AreSame(child.Resolve<IFoo>(), correctInstanceForIFooResolutionFromChild); Assert.AreSame(child.Resolve<Foo>(), correctInstanceForFooResolutionFromChild); Assert.AreSame(container.Resolve<Foo>(), fooResolvedFromMainContainer); Assert.AreSame(container.Resolve<SuperFoo>(), fooResolvedFromMainContainer); }
/// <summary> /// Registriert alle Services, welche im angegebenen Scope über das ServiceAttribut /// definiert sind. /// </summary> /// <param name = "scope">Service Scope</param> /// <returns>Der initialisierte Container</returns> protected static IUnityContainer RegisterDeclaredServices(ServiceScope scope) { var unityContainer = new UnityContainer(); foreach (ServiceContextAttribute type in ServiceAttribute.GetTypes(scope)) { switch (type.Behaviour) { case ServiceBehaviour.NewInstance: { if (!string.IsNullOrEmpty(type.InjectionParam)) unityContainer.RegisterType(type.RegisterFrom, type.RegisterTo, type.InjectionParam); else unityContainer.RegisterType(type.RegisterFrom, type.RegisterTo); break; } case ServiceBehaviour.Singleton: { var lfmr = new ContainerControlledLifetimeManager(); unityContainer.RegisterType(type.RegisterFrom, type.RegisterTo, lfmr); break; } case ServiceBehaviour.Webrequest: { if (scope == ServiceScope.Frontend) { RegisterPerWebRequest(type.RegisterFrom, type.RegisterTo, unityContainer); } else { var lfmr = new ContainerControlledLifetimeManager(); unityContainer.RegisterType(type.RegisterFrom, type.RegisterTo, lfmr); } break; } } } return unityContainer; }
public void RegisterTypeAfterRegisterInstanceDoesNotReusePreviousInstance() { var container = new QuickInjectContainer(); var foo = new Foo(); var foo2 = new Foo(); container.RegisterInstance<IFoo>(foo); var returnedInstance = container.Resolve<IFoo>(); var lifetime = new ContainerControlledLifetimeManager(); lifetime.SetValue(foo2); container.RegisterType<IFoo>(lifetime); var returnedInstance2 = container.Resolve<IFoo>(); Assert.AreNotSame(returnedInstance, returnedInstance2); }
public void LifetimeManagerWillProvideValueForAnInterfaceType() { var container = new QuickInjectContainer(); container.AddBuildPlanVisitor(new TransientLifetimeRemovalBuildPlanVisitor()); var lifetime = new ContainerControlledLifetimeManager(); var foo = new Foo(); lifetime.SetValue(foo); container.RegisterType<IFoo>(lifetime); var a = container.Resolve<IFoo>(); Assert.AreSame(a, foo); }
public void FuncOfTTest() { var container = new QuickInjectContainer(); container.AddBuildPlanVisitor(new TransientLifetimeRemovalBuildPlanVisitor()); var lifetime = new ContainerControlledLifetimeManager(); var foo = new Foo(); lifetime.SetValue(foo); container.RegisterType<IFoo>(lifetime); var a = container.Resolve<Func<IFoo>>(); Assert.AreSame(a(), foo); }