private int?GetTenantIdFromContributors() { foreach (var resolverType in _multiTenancy.Resolvers) { using (var resolver = _iocResolver.ResolveAsDisposable <ITenantResolveContributer>(resolverType)) { var tenantId = resolver.Object.ResolveTenantId(); if (tenantId == null) { continue; } if (_tenantStore.Find(tenantId.Value) == null) { continue; } return(tenantId); } } return(null); }
private static void WithDbContext <TDbContext>(IIocResolver iocResolver, Action <TDbContext> contextAction) where TDbContext : DbContext { //把新增的权限块设置给数据库 using (var uowManager = iocResolver.ResolveAsDisposable <IUnitOfWorkManager>()) { using (var uow = uowManager.Object.Begin(TransactionScopeOption.Suppress)) { try { var context = uowManager.Object.Current.GetDbContext <TDbContext>(MultiTenancySides.Host); contextAction(context); uow.Complete(); } catch (Exception e) { throw e; } } } }
protected virtual DbContextOptions <TDbContext> CreateOptions <TDbContext>([NotNull] string connectionString, [CanBeNull] DbConnection existingConnection) where TDbContext : DbContext { if (_iocResolver.IsRegistered <IAbpDbContextConfigurer <TDbContext> >()) { var configuration = new AbpDbContextConfiguration <TDbContext>(connectionString, existingConnection); configuration.DbContextOptions.ReplaceService <IEntityMaterializerSource, AbpEntityMaterializerSource>(); using (var configurer = _iocResolver.ResolveAsDisposable <IAbpDbContextConfigurer <TDbContext> >()) { configurer.Object.Configure(configuration); } return(configuration.DbContextOptions.Options); } if (_iocResolver.IsRegistered <DbContextOptions <TDbContext> >()) { return(_iocResolver.Resolve <DbContextOptions <TDbContext> >()); } throw new AbpException($"Could not resolve DbContextOptions for {typeof(TDbContext).AssemblyQualifiedName}."); }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { //当前方法或者控制器都没有定义校验特性,直接执行方法。 if (!_configuration.IsValidationEnabledForControllers || !context.ActionDescriptor.IsControllerAction()) { await next(); return; } //首先给当前方法增加拦截器记录,表示已经经过AbpCrossCuttingConcerns.Validation处理了。 using (AbpCrossCuttingConcerns.Applying(context.Controller, AbpCrossCuttingConcerns.Validation)) { using (var validator = _iocResolver.ResolveAsDisposable <MvcActionInvocationValidator>()) { //然后真正的调用Validate方法 validator.Object.Initialize(context); validator.Object.Validate(); } await next(); } }
/// <summary> /// 执行工作 /// </summary> /// <param name="jobInfo"></param> private void TryProcessJob(BackgroundJobInfo jobInfo) { try { jobInfo.TryCount++; jobInfo.LastTryTime = Clock.Now; var jobType = Type.GetType(jobInfo.JobType); using (var job = _iocResolver.ResolveAsDisposable(jobType)) { try { var jobExecuteMethod = job.Object.GetType().GetMethod("Execute"); var argsType = jobExecuteMethod.GetParameters()[0].ParameterType; var argsObj = JsonConvert.DeserializeObject(jobInfo.JobArgs, argsType); jobExecuteMethod.Invoke(job.Object, new[] { argsObj }); AsyncHelper.RunSync(() => _store.DeleteAsync(jobInfo)); } catch (Exception ex) { Logger.Warn(ex.Message, ex); var nextTryTime = jobInfo.CalculateNextTryTime(); if (nextTryTime.HasValue) { jobInfo.NextTryTime = nextTryTime.Value; } else { jobInfo.IsAbandoned = true; } TryUpdate(jobInfo); EventBus.Trigger( this, new AbpHandledExceptionData( new BackgroundJobException( "A background job execution is failed. See inner exception for details. See BackgroundJob property to get information on the background job.", ex ) { BackgroundJob = jobInfo, JobObject = job.Object } ) ); } } } catch (Exception ex) { Logger.Warn(ex.ToString(), ex); jobInfo.IsAbandoned = true; TryUpdate(jobInfo); } }
public virtual async Task PublishAsync( string notificationName, NotificationData data = null, EntityIdentifier entityIdentifier = null, NotificationSeverity severity = NotificationSeverity.Info, UserIdentifier[] userIds = null, UserIdentifier[] excludedUserIds = null, int?[] tenantIds = null) { if (notificationName.IsNullOrEmpty()) { throw new ArgumentException("NotificationName can not be null or whitespace!", nameof(notificationName)); } if (!tenantIds.IsNullOrEmpty() && !userIds.IsNullOrEmpty()) { throw new ArgumentException("tenantIds can be set only if userIds is not set!", nameof(tenantIds)); } if (tenantIds.IsNullOrEmpty() && userIds.IsNullOrEmpty()) { tenantIds = new[] { AbpSession.TenantId }; } var notificationInfo = new NotificationInfo(_guidGenerator.Create()) { NotificationName = notificationName, EntityTypeName = entityIdentifier?.Type.FullName, EntityTypeAssemblyQualifiedName = entityIdentifier?.Type.AssemblyQualifiedName, EntityId = entityIdentifier?.Id.ToJsonString(), Severity = severity, UserIds = userIds.IsNullOrEmpty() ? null : userIds.Select(uid => uid.ToUserIdentifierString()).JoinAsString(","), ExcludedUserIds = excludedUserIds.IsNullOrEmpty() ? null : excludedUserIds.Select(uid => uid.ToUserIdentifierString()).JoinAsString(","), TenantIds = GetTenantIdsAsStr(tenantIds), Data = data?.ToJsonString(), DataTypeName = data?.GetType().AssemblyQualifiedName }; await _store.InsertNotificationAsync(notificationInfo); await CurrentUnitOfWork.SaveChangesAsync(); //To get Id of the notification if (userIds != null && userIds.Length <= MaxUserCountToDirectlyDistributeANotification) { //We can directly distribute the notification since there are not much receivers foreach (var notificationDistributorType in _notificationConfiguration.Distributers) { using (var notificationDistributer = _iocResolver.ResolveAsDisposable <INotificationDistributer>(notificationDistributorType)) { await notificationDistributer.Object.DistributeAsync(notificationInfo.Id); } } } else { //We enqueue a background job since distributing may get a long time await _backgroundJobManager.EnqueueAsync <NotificationDistributionJob, NotificationDistributionJobArgs>( new NotificationDistributionJobArgs( notificationInfo.Id ) ); } }
private async Task TryProcessJobAsync(BackgroundJobInfo jobInfo) { try { jobInfo.TryCount++; jobInfo.LastTryTime = Clock.Now; var jobType = Type.GetType(jobInfo.JobType); using (var job = _iocResolver.ResolveAsDisposable(jobType)) { try { var jobExecuteMethod = job.Object.GetType().GetTypeInfo() .GetMethod(nameof(IBackgroundJob <object> .Execute)) ?? job.Object.GetType().GetTypeInfo() .GetMethod(nameof(IAsyncBackgroundJob <object> .ExecuteAsync)); if (jobExecuteMethod == null) { throw new AbpException( $"Given job type does not implement {typeof(IBackgroundJob<>).Name} or {typeof(IAsyncBackgroundJob<>).Name}. " + "The job type was: " + job.Object.GetType()); } var argsType = jobExecuteMethod.GetParameters()[0].ParameterType; var argsObj = JsonConvert.DeserializeObject(jobInfo.JobArgs, argsType); if (jobExecuteMethod.Name == nameof(IAsyncBackgroundJob <object> .ExecuteAsync)) { await((Task)jobExecuteMethod.Invoke(job.Object, new[] { argsObj })); } else { jobExecuteMethod.Invoke(job.Object, new[] { argsObj }); } await _store.DeleteAsync(jobInfo); } catch (Exception ex) { Logger.Warn(ex.Message, ex); var nextTryTime = jobInfo.CalculateNextTryTime(); if (nextTryTime.HasValue) { jobInfo.NextTryTime = nextTryTime.Value; } else { jobInfo.IsAbandoned = true; } await TryUpdateAsync(jobInfo); await EventBus.TriggerAsync( this, new AbpHandledExceptionData( new BackgroundJobException( "A background job execution is failed. See inner exception for details. See BackgroundJob property to get information on the background job.", ex ) { BackgroundJob = jobInfo, JobObject = job.Object } ) ); } } } catch (Exception ex) { Logger.Warn(ex.ToString(), ex); jobInfo.IsAbandoned = true; await TryUpdateAsync(jobInfo); } }
public IDisposableDependencyObjectWrapper <IExternalAuthProviderApi> CreateProviderApi(string provider) { ExternalLoginProviderInfo providerInfo = _externalAuthConfiguration.Providers.FirstOrDefault(p => p.Name == provider); if (providerInfo == null) { throw new Exception("Unknown external auth provider: " + provider); } IDisposableDependencyObjectWrapper <IExternalAuthProviderApi> providerApi = _iocResolver.ResolveAsDisposable <IExternalAuthProviderApi>(providerInfo.ProviderApiType); providerApi.Object.Initialize(providerInfo); return(providerApi); }
private static void WithDbContext <TDbContext>(IIocResolver iocResolver, Action <TDbContext> contextAction) where TDbContext : DbContext { using (IDisposableDependencyObjectWrapper <IUnitOfWorkManager> uowManager = iocResolver.ResolveAsDisposable <IUnitOfWorkManager>()) { using (IUnitOfWorkCompleteHandle uow = uowManager.Object.Begin(TransactionScopeOption.Suppress)) { TDbContext context = uowManager.Object.Current.GetDbContext <TDbContext>(MultiTenancySides.Host); contextAction(context); uow.Complete(); } } }