public T Resolve <T>() where T : IViewModel { var scope = _context.BeginLifetimeScope(); var viewModel = scope.Resolve <T>();; _viewModelsScopes.Add(viewModel, scope); return(viewModel); }
public async Task LifetimeScope_ResolveSingleton_ThreadSafe() { var subscope = LifetimeScope.BeginLifetimeScope(); var resolvingTasks = new List<Task<IInterface>> { Task.Run(() => subscope.ResolveRequiredService<IInterface>()), Task.Run(() => subscope.ResolveRequiredService<IInterface>()), Task.Run(() => subscope.ResolveRequiredService<IInterface>()), Task.Run(() => subscope.ResolveRequiredService<IInterface>()), Task.Run(() => subscope.ResolveRequiredService<IInterface>()), Task.Run(() => subscope.ResolveRequiredService<IInterface>()), Task.Run(() => subscope.ResolveRequiredService<IInterface>()), }; var interfaces = new List<IInterface>(); foreach (var task in resolvingTasks) interfaces.Add(await task); while (interfaces.Count > 1) { for (var i = 1; i < interfaces.Count; i++) Assert.Same(interfaces[0], interfaces[i]); interfaces.RemoveAt(0); } }
public void LifetimeScope_ResolvesSingleton_FromSubScope() { var instance1 = LifetimeScope.ResolveRequiredService <IInterface>(); var instance2 = LifetimeScope.BeginLifetimeScope().ResolveRequiredService <IInterface>(); Assert.Same(instance1, instance2); }
/// <summary> /// Configures all previously registered dependencies declared within the Register method of the specified /// IDependencyModule /// </summary> public void ConfigureModules(params object[] additionalServices) { if (LifetimeScope == null) { throw new Exception($"{nameof(ConfigureModules)} can only be called after build is complete"); } if (!_registeredModules.Any()) { throw new Exception("No dependency modules have been registered"); } using (var innerScope = LifetimeScope.BeginLifetimeScope(builder => { foreach (var additionalService in additionalServices) { builder.RegisterInstance(additionalService).AsImplementedInterfaces().SingleInstance(); } })) { //Resolve a new instance of the dependencies module foreach (var moduleType in _registeredModules.Keys.Except(_configuredModules)) { ConfigureModule(innerScope, moduleType); } } }
/// <inheritdoc /> public IDependencyScope CreateScope() { var testLifetime = LifetimeScope.BeginLifetimeScope(AutofacDependencyResolver.TestLifetimeScopeTag); var webRequestLifetime = testLifetime.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag); return(new NestedAutofacDependencyScope(testLifetime, webRequestLifetime)); }
public void LifetimeScope_SubScopes_Provides_Root_In_Constructor() { using var subscope = LifetimeScope.BeginLifetimeScope(); var disposable = subscope.ResolveRequiredService <SimpleSingleton>(); Assert.Same(LifetimeScope, disposable.LifetimeScope); }
public void LifetimeScope_Resolves_UniqueInstance_FromDifferentScopes() { using var subscope = LifetimeScope.BeginLifetimeScope(); object subject1 = LifetimeScope.ResolveRequiredService<IInterface>(); object subject2 = subscope.ResolveRequiredService<IInterface>(); Assert.NotEqual(subject1, subject2); }
public void LifetimeScope_ResolvesFromSubscope_ToSingleInstance() { using var subscope = LifetimeScope.BeginLifetimeScope(); object subject1 = subscope.ResolveRequiredService<IInterface>(); object subject2 = subscope.ResolveRequiredService<IInterface>(); Assert.Equal(subject1, subject2); }
public void LifetimeScope_Resolves_IServiceProvider() { IServiceProvider res1 = LifetimeScope.ResolveRequiredService <IServiceProvider>(); Assert.Same(LifetimeScope, res1); IServiceProvider subscope = LifetimeScope.BeginLifetimeScope(); IServiceProvider res2 = subscope.ResolveRequiredService <IServiceProvider>(); Assert.Same(subscope, res2); }
public void LifetimeScope_Resolves_ILifetimeScope() { ILifetimeScope res1 = LifetimeScope.ResolveRequiredService <ILifetimeScope>(); Assert.Same(LifetimeScope, res1); ILifetimeScope subscope = LifetimeScope.BeginLifetimeScope(); ILifetimeScope res2 = subscope.ResolveRequiredService <ILifetimeScope>(); Assert.Same(subscope, res2); }
public void LifetimeScope_Disposes_SubScopes() { ILifetimeScope subscope = LifetimeScope.BeginLifetimeScope(); Assert.False(LifetimeScope.IsDisposed); Assert.False(subscope.IsDisposed); LifetimeScope.Dispose(); Assert.True(LifetimeScope.IsDisposed); Assert.True(subscope.IsDisposed); }
public void LifetimeScope_Only_Disposes_Children() { ILifetimeScope subscope = LifetimeScope.BeginLifetimeScope(); var instance = LifetimeScope.ResolveRequiredService <Disposable>(); var subInstance = subscope.ResolveRequiredService <Disposable>(); Assert.False(subInstance.IsDisposed); subscope.Dispose(); Assert.True(subInstance.IsDisposed); Assert.False(instance.IsDisposed); }
/// <summary> /// Callback which is fired when connection has been made to controller/method. /// </summary> /// <param name="hubDescriptor"></param> /// <param name="request"></param> /// <returns></returns> public bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) { // Whether anonymous access is allowed or not. if (IsAnonymousAllowed(hubDescriptor)) { return(true); } using (var lifeTimeScope = LifetimeScope.BeginLifetimeScope()) { return(IsAccessible(lifeTimeScope, request)); } }
/// <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); } } }
/// <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> /// Callback which is fired when user is invoking controller/method. /// </summary> /// <param name="hubIncomingInvokerContext"></param> /// <param name="appliesToMethod"></param> /// <returns></returns> public bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod) { var hub = hubIncomingInvokerContext.Hub; var request = hub.Context.Request; var hubDescriptor = hubIncomingInvokerContext.MethodDescriptor.Hub; // Whether anonymous access is allowed or not. if (IsAnonymousAllowed(hubDescriptor)) { return(true); } using (var lifeTimeScope = LifetimeScope.BeginLifetimeScope()) { // Search logging service. var log = lifeTimeScope.Resolve <ILog>(); #region Request validation if (request.User == null) { InitiateErrorMessage(log, "No user identity has been attached to the request."); return(false); } if (request.User.Identity == null) { InitiateErrorMessage(log, "No user identity has been attached to the request."); return(false); } #endregion return(IsAccessible(lifeTimeScope, request)); } }
public void PreProcess() { GlobalContext = new GlobalContext(LifetimeScope.BeginLifetimeScope(), RootElements); Processor.PreProcess(GlobalContext); }
public IDependencyScope BeginScope() { var lifetimeScope = LifetimeScope.BeginLifetimeScope(); return(new AutofacWebApiDependencyScope(lifetimeScope)); }
/// <summary> /// Begin a new sub-scope. Instances created via the sub-scope /// will be disposed along with it. /// </summary> /// <returns>A new lifetime scope.</returns> public ILifetimeScope BeginLifetimeScope() { return(_rootLifetimeScope.BeginLifetimeScope()); }
private FM35Global RunFunding(FundingDto actorModel, CancellationToken cancellationToken) { if (ExecutionContext is ExecutionContext executionContextObj) { executionContextObj.JobId = "-1"; executionContextObj.TaskKey = ActorId.ToString(); } ILogger logger = LifetimeScope.Resolve <ILogger>(); IExternalDataCache externalDataCache; FM35Global results; try { logger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} starting"); externalDataCache = BuildExternalDataCache(actorModel.ExternalDataCache); logger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} finished getting input data"); cancellationToken.ThrowIfCancellationRequested(); } catch (Exception ex) { ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString()); logger.LogError($"Error while processing {nameof(FM35Actor)}", ex); throw; } using (var childLifetimeScope = LifetimeScope.BeginLifetimeScope(c => { c.RegisterInstance(externalDataCache).As <IExternalDataCache>(); })) { ExecutionContext executionContext = (ExecutionContext)childLifetimeScope.Resolve <IExecutionContext>(); executionContext.JobId = actorModel.JobId.ToString(); executionContext.TaskKey = ActorId.ToString(); ILogger jobLogger = childLifetimeScope.Resolve <ILogger>(); try { jobLogger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} started processing"); IFundingService <FM35LearnerDto, FM35Global> fundingService = childLifetimeScope.Resolve <IFundingService <FM35LearnerDto, FM35Global> >(); var learners = BuildLearners <FM35LearnerDto>(actorModel.ValidLearners); results = fundingService.ProcessFunding(actorModel.UKPRN, learners, cancellationToken); jobLogger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} completed processing"); } catch (Exception ex) { ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString()); jobLogger.LogError($"Error while processing {nameof(FM35Actor)}", ex); throw; } } externalDataCache = null; return(results); }
private FM25Global RunFunding(FundingDto actorModel, CancellationToken cancellationToken) { if (ExecutionContext is ExecutionContext executionContextObj) { executionContextObj.JobId = "-1"; executionContextObj.TaskKey = ActorId.ToString(); } ILogger logger = LifetimeScope.Resolve <ILogger>(); IExternalDataCache externalDataCache; FM25Global condensedResults; try { logger.LogDebug($"{nameof(FM25Actor)} {ActorId} starting"); externalDataCache = BuildExternalDataCache(actorModel.ExternalDataCache); logger.LogDebug($"{nameof(FM25Actor)} {ActorId} finished getting input data"); cancellationToken.ThrowIfCancellationRequested(); } catch (Exception ex) { ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString()); logger.LogError($"Error while processing {nameof(FM25Actor)}", ex); throw; } using (var childLifetimeScope = LifetimeScope.BeginLifetimeScope(c => { c.RegisterInstance(externalDataCache).As <IExternalDataCache>(); })) { ExecutionContext executionContext = (ExecutionContext)childLifetimeScope.Resolve <IExecutionContext>(); executionContext.JobId = actorModel.JobId.ToString(); executionContext.TaskKey = ActorId.ToString(); ILogger jobLogger = childLifetimeScope.Resolve <ILogger>(); try { jobLogger.LogDebug($"{nameof(FM25Actor)} {ActorId} {GC.GetGeneration(actorModel)} started processing"); IEnumerable <FM25Global> fm25Results; IEnumerable <PeriodisationGlobal> fm25PeriodisationResults; using (var fundingServiceLifetimeScope = childLifetimeScope.BeginLifetimeScope(c => { c.RegisterInstance(new FM25RulebaseProvider()).As <IRulebaseStreamProvider <FM25LearnerDto> >(); })) { jobLogger.LogDebug("FM25 Rulebase Starting"); IFundingService <FM25LearnerDto, IEnumerable <FM25Global> > fundingService = fundingServiceLifetimeScope.Resolve <IFundingService <FM25LearnerDto, IEnumerable <FM25Global> > >(); var learners = BuildLearners <FM25LearnerDto>(actorModel.ValidLearners); fm25Results = fundingService.ProcessFunding(actorModel.UKPRN, learners, cancellationToken).ToList(); jobLogger.LogDebug("FM25 Rulebase Finishing"); } using (var fundingServiceLifetimeScope = childLifetimeScope.BeginLifetimeScope(c => { c.RegisterInstance(new FM25PeriodisationRulebaseProvider()).As <IRulebaseStreamProvider <FM25Global> >(); })) { jobLogger.LogDebug("FM25 Periodisation Rulebase Starting"); IFundingService <FM25Global, IEnumerable <PeriodisationGlobal> > periodisationService = fundingServiceLifetimeScope.Resolve <IFundingService <FM25Global, IEnumerable <PeriodisationGlobal> > >(); fm25PeriodisationResults = periodisationService.ProcessFunding(actorModel.UKPRN, fm25Results, cancellationToken).ToList(); jobLogger.LogDebug("FM25 Periodisation Rulebase Finishing"); IFM25FundingOutputCondenserService <FM25Global, PeriodisationGlobal> condenser = fundingServiceLifetimeScope.Resolve <IFM25FundingOutputCondenserService <FM25Global, PeriodisationGlobal> >(); condensedResults = condenser.CondensePeriodisationResults(fm25Results, fm25PeriodisationResults); } jobLogger.LogDebug($"{nameof(FM25Actor)} {ActorId} {GC.GetGeneration(actorModel)} completed processing"); } catch (Exception ex) { ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString()); jobLogger.LogError($"Error while processing {nameof(FM25Actor)}", ex); throw; } } externalDataCache = null; return(condensedResults); }
/// <inheritdoc /> public IDependencyScope CreateScope() { return(new AutofacDependencyScope(LifetimeScope.BeginLifetimeScope(TestLifetimeScopeTag))); }
public ILifetimeScope BeginLifetimeScope(object tag, Action <ContainerBuilder> configurationAction) { return(LifetimeScope.BeginLifetimeScope(tag, configurationAction)); }
public ILifetimeScope BeginLifetimeScope(Action <ContainerBuilder> configurationAction) { return(LifetimeScope.BeginLifetimeScope(configurationAction)); }
public ILifetimeScope BeginLifetimeScope(object tag) { return(LifetimeScope.BeginLifetimeScope(tag)); }