public async Task TestFindById() { var userName = "******"; var appUser = new AppUser { UserName = userName }; Connection.FirstOrDefault <AppUser>(null).ReturnsForAnyArgs(appUser); var userStore = LifetimeScope.Resolve <AppUserStore>(); var result = await userStore.FindByIdAsync(appUser.Id, CancellationToken.None); Assert.That(result.Id, Is.EqualTo(appUser.Id)); Assert.That(result.UserName, Is.EqualTo(userName)); await Connection.Received(1).FirstOrDefault <AppUser>(Arg.Is <string>(x => x == $"SELECT * FROM UserTable WHERE Id = '{appUser.Id}'")); }
public IEnumerator StartableExceptionHandler() { var handled = 0; LifetimeScope.Create(builder => { builder.RegisterEntryPoint <StartableThrowable>(); builder.RegisterEntryPointExceptionHandler(ex => { handled += 1; }); }); yield return(null); yield return(null); Assert.That(handled, Is.EqualTo(1)); }
public void RegisterComponentInHierarchyWithBuiltinType() { var go1 = new GameObject("Parent"); go1.AddComponent <BoxCollider>(); var lifetimeScope = LifetimeScope.Create(builder => { builder.Register <ServiceA>(Lifetime.Transient); builder.RegisterComponentInHierarchy <BoxCollider>(); }); var resolved = lifetimeScope.Container.Resolve <BoxCollider>(); Assert.That(resolved, Is.InstanceOf <BoxCollider>()); }
public IDependencyContainerV2 BeginScope(LifetimeScope scope, Action <ContainerConfigurator> configuration = null) { var innerScope = new AutofacContainer(); var autofacScope = scope.Equals(LifetimeScope.Local) ? new object() : scope; innerScope.AutofacScope = AutofacScope.BeginLifetimeScope(autofacScope, builder => { new AutofacContainerBuilder(builder).Configure(configuration); innerScope.RegisterSelf(builder); }); return(innerScope); }
public override void Register <TRegisteredAs, TResolvedTo>(LifetimeScope lifetimeScope, string name) { // Http is the default for Autofac ASP.NET integrations. Instance per dependency otherwise. ContainerBuilder builder = new ContainerBuilder(); if (TryResolve <TRegisteredAs>() != null) { builder.RegisterType <TResolvedTo>().Named <TRegisteredAs>(name).SetLifeStyle(lifetimeScope).PreserveExistingDefaults(); } else { builder.RegisterType <TResolvedTo>().Named <TRegisteredAs>(name).SetLifeStyle(lifetimeScope); } builder.Update(Container); }
public IEnumerator CreateChild() { var parentLifetimeScope = LifetimeScope.Create(builder => { builder.RegisterEntryPoint <SampleEntryPoint>(Lifetime.Scoped).AsSelf(); }); yield return(null); yield return(null); var parentEntryPoint = parentLifetimeScope.Container.Resolve <SampleEntryPoint>(); var parentLifetimeScopeFromContainer = parentLifetimeScope.Container.Resolve <LifetimeScope>(); Assert.That(parentLifetimeScopeFromContainer, Is.EqualTo(parentLifetimeScope)); Assert.That(parentLifetimeScopeFromContainer.transform.childCount, Is.Zero); Assert.That(parentEntryPoint, Is.InstanceOf <SampleEntryPoint>()); Assert.That(parentEntryPoint.InitializeCalled, Is.True); Assert.That(parentEntryPoint.TickCalls, Is.EqualTo(2)); var childLifetimeScope = parentLifetimeScope.CreateChild(builder => { builder.RegisterEntryPoint <SampleEntryPoint>(Lifetime.Scoped).AsSelf(); builder.Register <DisposableServiceA>(Lifetime.Scoped); }); yield return(null); yield return(null); var childEntryPoint = childLifetimeScope.Container.Resolve <SampleEntryPoint>(); var childDisposable = childLifetimeScope.Container.Resolve <DisposableServiceA>(); var childLifetimeScopeFromContainer = childLifetimeScope.Container.Resolve <LifetimeScope>(); Assert.That(childLifetimeScopeFromContainer, Is.EqualTo(childLifetimeScope)); Assert.That(childEntryPoint, Is.InstanceOf <SampleEntryPoint>()); Assert.That(childEntryPoint, Is.Not.EqualTo(parentEntryPoint)); Assert.That(childEntryPoint.InitializeCalled, Is.True); Assert.That(childEntryPoint.TickCalls, Is.EqualTo(2)); childLifetimeScope.Dispose(); yield return(null); Assert.That(childDisposable.Disposed, Is.True); Assert.That(childLifetimeScope == null, Is.True); Assert.That(parentLifetimeScope.transform.childCount, Is.Zero); }
public void Even_if_container_does_not_track_dependecies_should_release_dependency_when_exiting_the_scope() { var container = new WindsorContainer(); container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy(); container.Register(Component .For<ISimpleService>() .ImplementedBy<SimpleServiceImpl>() .LifeStyle.Custom<PerLifetimeScopeLifestyle<string>>()); SimpleServiceImpl service; using(var scope = new LifetimeScope<string>()) { service = (SimpleServiceImpl)container.Resolve<ISimpleService>(); } Assert.AreEqual(1, service.TimesDisposed); }
public async Task TestCreateAsync() { var appUser = new AppUser { UserName = "******", PasswordHash = "a", SecurityStamp = "b", UserGroupId = 1 }; Connection.Execute(Arg.Any <string>()).ReturnsForAnyArgs(Task.FromResult); var userStore = LifetimeScope.Resolve <AppUserStore>(); await userStore.CreateAsync(appUser, CancellationToken.None); await Connection.Received(1).Execute(Arg.Is <string>(x => x == $"INSERT INTO UserTable(Id, UserName, CreateDate, PasswordHash, SecurityStamp, UserGroupId) VALUES ('{appUser.Id}', '{appUser.UserName}', '{appUser.CreateDate}', '{appUser.PasswordHash}', '{appUser.SecurityStamp}', '{appUser.UserGroupId}')")); }
/// <summary> /// Gets the reuse. /// </summary> /// <param name="lifetimeScope">The lifetime scope.</param> /// <returns></returns> private IReuse GetReuse(LifetimeScope lifetimeScope) { switch (lifetimeScope) { case LifetimeScope.Unowned: return(Reuse.Transient); case LifetimeScope.PerHttpRequest: return(Reuse.InWebRequest); case LifetimeScope.PerThread: return(Reuse.InThread); default: return(Reuse.Transient); } }
public void CreateScopeWithSingleton() { var parentLifetimeScope = LifetimeScope.Create(builder => { builder.RegisterEntryPoint <SampleEntryPoint>(Lifetime.Singleton).AsSelf(); }); var parentEntryPoint = parentLifetimeScope.Container.Resolve <SampleEntryPoint>(); Assert.That(parentEntryPoint, Is.InstanceOf <SampleEntryPoint>()); var childLifetimeScope = parentLifetimeScope.CreateChild(); var childEntryPoint = childLifetimeScope.Container.Resolve <SampleEntryPoint>(); Assert.That(childEntryPoint, Is.InstanceOf <SampleEntryPoint>()); Assert.That(childEntryPoint, Is.EqualTo(parentEntryPoint)); }
public async Task TestUpdateAsync() { var appUser = new AppUser { UserName = "******", PasswordHash = "a", SecurityStamp = "b", UserGroupId = 1 }; Connection.Execute(Arg.Any <string>()).ReturnsForAnyArgs(Task.FromResult); var userStore = LifetimeScope.Resolve <AppUserStore>(); await userStore.UpdateAsync(appUser, CancellationToken.None); await Connection.Received(1).Execute(Arg.Is <string>(x => x == $"UPDATE UserTable SET UserName = '******', CreateDate = '{appUser.CreateDate}', PasswordHash = '{appUser.PasswordHash}', SecurityStamp = '{appUser.SecurityStamp}', UserGroupId = '{appUser.UserGroupId}' WHERE Id = '{appUser.Id}'")); }
/// <summary> /// Gets the lifestyle. /// </summary> /// <param name="scope">The scope.</param> /// <returns></returns> private Lifestyle GetLifestyle(LifetimeScope scope) { switch (scope) { case LifetimeScope.Unowned: return(Lifestyle.Transient); case LifetimeScope.PerHttpRequest: return(WebRequestWithDisposal); case LifetimeScope.PerThread: return(ExecutionContextWithDisposal); default: return(Lifestyle.Transient); } }
protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { LifetimeScope.Dispose(); } Settings = null; Descriptor = null; Blueprint = null; Shell = null; _disposed = true; } }
private LifetimeManager GetLifetimeManager(LifetimeScope lifetimeScope) { switch (lifetimeScope) { case LifetimeScope.Unowned: return(new TransientLifetimeManager()); case LifetimeScope.PerHttpRequest: return(new PerRequestLifetimeManager()); case LifetimeScope.PerThread: return(new PerThreadLifetimeManager()); default: return(new TransientLifetimeManager()); } }
/// <summary> /// Callback which is fired when a client connected /// </summary> /// <returns></returns> public override async Task OnConnected() { // Search account from request. var httpContext = Context.Request.GetHttpContext(); // Http context is invalid. if (httpContext == null) { return; } // Search account from request. var account = (Account)httpContext.Items[ClaimTypes.Actor]; if (account == null) { return; } // Begin new life time scope. using (var lifeTimeScope = LifetimeScope.BeginLifetimeScope()) { // Search unit of work of life time scope. var unitOfWork = lifeTimeScope.Resolve <IUnitOfWork>(); var timeService = lifeTimeScope.Resolve <ITimeService>(); try { // Search and update connection to the account. var signalrConnection = new SignalrConnection(); signalrConnection.OwnerIndex = account.Id; signalrConnection.Index = Context.ConnectionId; signalrConnection.Created = timeService.DateTimeUtcToUnix(DateTime.UtcNow); unitOfWork.RepositorySignalrConnections.Insert(signalrConnection); await unitOfWork.CommitAsync(); Log.Info( $"Connection (Id: {Context.ConnectionId}) has been established from account (Email: {account.Email})"); } catch (Exception exception) { Log.Error(exception.Message, exception); } } }
public IEnumerator AsyncStartupCancellable() => UniTask.ToCoroutine(async() => { var lifetimeScope = LifetimeScope.Create(builder => { builder.RegisterEntryPoint <SampleAsyncStartableCancellable>(Lifetime.Scoped) .AsSelf(); }); var entryPoint = lifetimeScope.Container.Resolve <SampleAsyncStartableCancellable>(); Assert.That(entryPoint.Started, Is.False); lifetimeScope.Dispose(); await UniTask.Yield(); await UniTask.Yield(); Assert.That(entryPoint.Started, Is.False); Assert.That(entryPoint.Cancelled, Is.False); });
/// <summary> /// Create a new container. /// </summary> internal Container() { _componentRegistry = new ComponentRegistry(); _componentRegistry.Register(new ComponentRegistration( LifetimeScope.SelfRegistrationId, new DelegateActivator(typeof(LifetimeScope), (c, p) => { throw new InvalidOperationException("The container's self-registration of context interfaces should never be activated as it is hard-wired into the LifetimeScope class."); }), new CurrentScopeLifetime(), InstanceSharing.Shared, InstanceOwnership.ExternallyOwned, new Service[] { new TypedService(typeof(ILifetimeScope)), new TypedService(typeof(IComponentContext)) }, new Dictionary <string, object>())); _rootLifetimeScope = new LifetimeScope(_componentRegistry); }
public override void GetInstance(LifetimeScope lifetimeScope, Func <object> valueFactory, Type valueType, out object value) { object requestedInstance; this.scope.GetInstance(lifetimeScope, valueFactory, valueType, out requestedInstance); if (typeContext.Modules.ContainsKey(valueType)) { typeContext.Modules[valueType].RegisteredInstanceResolved(valueType, requestedInstance); } foreach (var module in this.allModules) { module.InstanceResolved(valueType, requestedInstance); } value = requestedInstance; }
public IEnumerator AsyncStartupExceptionHandler() => UniTask.ToCoroutine(async() => { Exception caught = null; var lifetimeScope = LifetimeScope.Create(builder => { builder.RegisterEntryPoint <SampleAsyncStartableThrowable>(Lifetime.Scoped) .AsSelf(); builder.RegisterEntryPointExceptionHandler(ex => caught = ex); }); var entryPoint = lifetimeScope.Container.Resolve <SampleAsyncStartableThrowable>(); Assert.That(entryPoint, Is.InstanceOf <SampleAsyncStartableThrowable>()); await UniTask.Yield(); await UniTask.Yield(); Assert.That(caught, Is.InstanceOf <InvalidOperationException>()); });
/// <summary> /// Create a new container. /// </summary> internal Container() { _componentRegistry = new ComponentRegistry(); _componentRegistry.Register(new ComponentRegistration( LifetimeScope.SelfRegistrationId, new DelegateActivator(typeof(LifetimeScope), (c, p) => { throw new InvalidOperationException(ContainerResources.SelfRegistrationCannotBeActivated); }), new CurrentScopeLifetime(), InstanceSharing.Shared, InstanceOwnership.ExternallyOwned, new Service[] { new TypedService(typeof(ILifetimeScope)), new TypedService(typeof(IComponentContext)) }, new Dictionary <string, object>())); _rootLifetimeScope = new LifetimeScope(_componentRegistry); }
internal MiniContainer() { ComponentRegistry = new ComponentRegistry(); ComponentRegistry.Register(new ComponentRegistration( LifetimeScope.SelfScopeId, new DelegateActivator(typeof(LifetimeScope), c => throw MiniException.UnExpectedOperated( typeof(MiniContainer), $"root can't resolve {typeof(ILifetimeScope).FullName}, {typeof(IComponentContext)}")), new CurrentLifetimeScope(), InstanceSharing.Shared, new TypedService(typeof(ILifetimeScope)), new TypedService(typeof(IComponentContext) ))); RootLifetimeScope = new LifetimeScope(ComponentRegistry); }
public IEnumerator DispatchMonoBehaviour() { var component = new GameObject("SampleBehaviour").AddComponent <SampleMonoBehaviour>(); using (LifetimeScope.Enqueue(bulder => { bulder.Register <ServiceA>(Lifetime.Transient); bulder.RegisterComponent(component); })) { new GameObject("LifetimeScope").AddComponent <LifetimeScope>(); } yield return(null); Assert.That(component.ServiceA, Is.InstanceOf <ServiceA>()); Assert.That(component.StartCalled, Is.True); Assert.That(component.UpdateCalls, Is.GreaterThanOrEqualTo(1)); }
public ApplicationsViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher) : base(lifetimeScope, dispatcher) { var modelView = LifetimeScope.Resolve <IViewModel <ApplicationManagerTabViewModel> >(); modelView.InitModel(Context, "Application_Manager"); Items = this.RegisterUiCollection <TabItem>(nameof(Items)) .AndInitialElements(new TabItem(LocLocalizer.Inst.ApplicationsView.GlobalManagerHeader, modelView)) .AndAsync(); CurrentTab = RegisterProperty <int>(nameof(CurrentTab)); var hostApi = HostApi.CreateOrGet(Context.System); AddResource(hostApi.Event <HostEntryChanged>()); Receive <HostEntryChanged>(e => {
public void Even_if_container_does_not_track_dependecies_should_release_dependency_when_exiting_the_scope() { var container = new WindsorContainer(); container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy(); container.Register(Component .For <ISimpleService>() .ImplementedBy <SimpleServiceImpl>() .LifeStyle.Custom <PerLifetimeScopeLifestyle <string> >()); SimpleServiceImpl service; using (var scope = new LifetimeScope <string>()) { service = (SimpleServiceImpl)container.Resolve <ISimpleService>(); } Assert.AreEqual(1, service.TimesDisposed); }
public void CreateChildFromPrefab() { var parent = LifetimeScope.Create(builder => { builder.RegisterEntryPoint <SampleEntryPoint>().AsSelf(); }); var childPrefab = new GameObject("Child").AddComponent <SampleChildLifetimeScope>(); var child = parent.CreateChildFromPrefab(childPrefab); var parentResolved = parent.Container.Resolve <SampleEntryPoint>(); var childResolved = child.Container.Resolve <SampleEntryPoint>(); Assert.That(parentResolved, Is.InstanceOf <SampleEntryPoint>()); Assert.That(childResolved, Is.InstanceOf <SampleEntryPoint>()); Assert.That(childResolved, Is.EqualTo(parentResolved)); Assert.That(child.parentReference.Object, Is.EqualTo(parent)); Assert.That(childPrefab.gameObject.activeSelf, Is.True); }
private LifetimeManager GetLifetimeManager(LifetimeScope lifetimeScope) { switch (lifetimeScope) { case LifetimeScope.Unowned: return(new TransientLifetimeManager()); case LifetimeScope.Singleton: // todo: check this return(new ContainerControlledLifetimeManager()); case LifetimeScope.PerHttpRequest: return(new TransientLifetimeManager()); case LifetimeScope.PerThread: return(new PerThreadLifetimeManager()); default: return(new TransientLifetimeManager()); } }
/// <summary> /// Callback which is fired when a client disconnected from /// </summary> /// <param name="stopCalled"></param> /// <returns></returns> public override async Task OnDisconnected(bool stopCalled) { using (var lifeTimeScope = LifetimeScope.BeginLifetimeScope()) { // Search unit of work from life time scope. var unitOfWork = lifeTimeScope.Resolve <IUnitOfWork>(); // Search for record whose index is the same as connection index. var condition = new FindSignalrConnectionViewModel(); condition.Index = new TextSearch(); condition.Index.Mode = TextComparision.EqualIgnoreCase; condition.Index.Value = Context.ConnectionId; // Find connections with specific conditions. var connections = unitOfWork.RepositorySignalrConnections.Search(); connections = unitOfWork.RepositorySignalrConnections.Search(connections, condition); unitOfWork.RepositorySignalrConnections.Remove(connections); await unitOfWork.CommitAsync(); } }
public void Register(IUnitOfWorkRegisteration unitOfWorkRegisteration) { if (IsDisposed) { throw new InvalidOperationException("UnitOfWork provider has been already disposed"); } lock (UnitOfWorkCreators) { ILifetimeScope childScope = LifetimeScope.BeginLifetimeScope(containerBuilder => { containerBuilder.RegisterType(unitOfWorkRegisteration.UnitOfWorkCreatorType) .As <IUnitOfWorkCreator>() .SingleInstance(); unitOfWorkRegisteration.Initialize(containerBuilder); }); IUnitOfWorkCreator unitOfWorkCreator = childScope.Resolve <IUnitOfWorkCreator>(TypedParameter.From(childScope)); UnitOfWorkCreators.Add(unitOfWorkRegisteration.Name, unitOfWorkCreator); } }
/// <summary> /// Resolves the specified target. /// </summary> /// <param name="target">The target.</param> /// <param name="lifetimeScope">The lifetimeScope.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">Fata error: List instance doesn't implements IList interface.</exception> /// <exception cref="System.NotSupportedException">Not supported yet.</exception> public override object Resolve(Type target, LifetimeScope lifetimeScope, object key = null) { var hiddenType = target.GetGenericArguments()[0]; var outputList = lifetimeScope.Container.ActivationEngine(ActivatorDataForList(hiddenType)) as IList; if (outputList == null) { throw new InvalidOperationException("Fata error: List instance doesn't implements IList interface."); } if (lifetimeScope.Container.ResolveImplicit) { throw new NotSupportedException("Not supported yet."); } if (!lifetimeScope.Container.TypeContainer.ContainsKey(hiddenType)) { throw new InvalidOperationException("Enumerable argument type not registered."); } var typeContext = lifetimeScope.Container.TypeContainer[hiddenType]; foreach (var outputType in typeContext.GetForKey(key)) { var scope = this.WrapScope(lifetimeScope, typeContext, typeContext.Scopes[outputType]); object instance; scope.GetInstance(lifetimeScope, () => { var ctx = lifetimeScope.Container.TypeContainer[hiddenType]; return(lifetimeScope.Container.CreateInstanceRecursive(lifetimeScope, ctx, outputType, target)); }, outputType, out instance); outputList.Add(instance); } return(outputList); }
public void UseComponentsWithParentTransform() { var go1 = new GameObject("Parent"); var go2 = new GameObject("Child A"); var go3 = new GameObject("Child B"); go3.transform.SetParent(go2.transform); go2.transform.SetParent(go1.transform); go1.AddComponent <SampleMonoBehaviour>(); go3.AddComponent <SampleMonoBehaviour>(); var lifetimeScope = LifetimeScope.Create(builder => { builder.Register <ServiceA>(Lifetime.Scoped); builder.Register <ServiceB>(Lifetime.Scoped); builder.UseComponents(go2.transform, components => { components.AddInHierarchy <SampleMonoBehaviour>(); }); builder.UseComponents(go3.transform, components => { components.AddOnNewGameObject <SampleMonoBehaviour2>(Lifetime.Scoped); }); }); var found = lifetimeScope.Container.Resolve <SampleMonoBehaviour>(); Assert.That(found, Is.InstanceOf <SampleMonoBehaviour>()); Assert.That(found.transform.parent, Is.EqualTo(go2.transform)); var created = lifetimeScope.Container.Resolve <SampleMonoBehaviour2>(); Assert.That(created, Is.InstanceOf <SampleMonoBehaviour2>()); Assert.That(created.transform.parent, Is.EqualTo(go3.transform)); }
public void UpdateFrom(LifetimeScopeBeginningMessage message) { if (message == null) { throw new ArgumentNullException("message"); } LifetimeScope parent = null; if (message.LifetimeScope.ParentLifetimeScopeId != null) { _lifetimeScopes.TryGetItem(message.LifetimeScope.ParentLifetimeScopeId, out parent); } var lifetimeScope = new LifetimeScope(message.LifetimeScope.Id, TagFor(message.LifetimeScope), parent); _lifetimeScopes.Add(lifetimeScope); if (parent != null) { parent.ActiveChildren.Add(lifetimeScope); } }