public override INHibernateProxy GetProxy(object id, ISessionImplementor session) { INHibernateProxy proxy; try { var behaviorInfo = _behaviorConfigurator.GetProxyInformation(PersistentClass); var initializer = new LazyInitializer(EntityName, PersistentClass, id, GetIdentifierMethod, SetIdentifierMethod, ComponentIdType, session); IInterceptor[] interceptors = behaviorInfo.Interceptors .Select(i => _kernel.Resolve(i)) .OfType<IInterceptor>() .Union(new[] {initializer}).ToArray(); Type[] interfaces = Interfaces.Union(behaviorInfo.AdditionalInterfaces).ToArray(); object obj2 = IsClassProxy ? ProxyGenerator.CreateClassProxy(PersistentClass, interfaces, interceptors) : ProxyGenerator.CreateInterfaceProxyWithoutTarget(interfaces[0], interfaces, new IInterceptor[] {initializer}); initializer._constructed = true; proxy = (INHibernateProxy) obj2; } catch (Exception exception) { log.Error("Creating a proxy instance failed", exception); throw new HibernateException("Creating a proxy instance failed", exception); } return proxy; }
public override INHibernateProxy GetProxy(object id, global::NHibernate.Engine.ISessionImplementor session) { try { var initializer = new LazyInitializer(EntityName, PersistentClass, id, GetIdentifierMethod, SetIdentifierMethod, ComponentIdType, session); object generatedProxy = IsClassProxy ? DataBindingFactory.Create(PersistentClass, Interfaces, initializer) : ProxyGenerator.CreateInterfaceProxyWithoutTarget(Interfaces[0], Interfaces, initializer); initializer._constructed = true; return (INHibernateProxy) generatedProxy; } catch (Exception e) { throw new HibernateException("Creating a proxy instance failed", e); } }
public override INHibernateProxy GetProxy(object id, ISessionImplementor session) { try { var initializer = new LazyInitializer(EntityName, PersistentClass.IsInterface ? typeof (object) : PersistentClass, id, GetIdentifierMethod, SetIdentifierMethod, ComponentIdType, session); var proxyFactory = new SerializableProxyFactory {Interfaces = Interfaces, TargetSource = initializer, ProxyTargetType = IsClassProxy}; proxyFactory.AddAdvice(initializer); object proxyInstance = proxyFactory.GetProxy(); return (INHibernateProxy) proxyInstance; } catch (Exception ex) { log.Error("Creating a proxy instance failed", ex); throw new HibernateException("Creating a proxy instance failed", ex); } }
public IKey GetPrimaryKey() { return(LazyInitializer.EnsureInitialized(ref _key, LoadKey)); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // Обеспечение однократной инициализации ASP.NET Simple Membership при каждом запуске приложения LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // 确保每次启动应用程序时只初始化一次 ASP.NET Simple Membership LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); }
/// <summary>Gets the lazily-initialized completion state.</summary> private CompletionState EnsureCompletionStateInitialized() { // ValueLock not needed, but it's ok if it's held return(LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState())); }
public static void EnsureInitialized_ComplexRefTypes() { string strTemplate = "foo"; var hdcTemplate = new HasDefaultCtor(); // Activator.CreateInstance (uninitialized). HasDefaultCtor a = null; bool aInit = false; object aLock = null; Assert.NotNull(LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock)); Assert.NotNull(a); Assert.True(aInit); Assert.NotNull(aLock); // Activator.CreateInstance (already initialized). HasDefaultCtor b = hdcTemplate; bool bInit = true; object bLock = null; Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock)); Assert.Equal(hdcTemplate, b); Assert.True(bInit); Assert.Null(bLock); // Func based initialization (uninitialized). string c = null; bool cInit = false; object cLock = null; Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => strTemplate)); Assert.Equal(strTemplate, c); Assert.True(cInit); Assert.NotNull(cLock); // Func based initialization (already initialized). string d = strTemplate; bool dInit = true; object dLock = null; Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => strTemplate + "bar")); Assert.Equal(strTemplate, d); Assert.True(dInit); Assert.Null(dLock); // Func based initialization (nulls *ARE* permitted). string e = null; bool einit = false; object elock = null; int initCount = 0; Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return(null); })); Assert.Null(e); Assert.Equal(1, initCount); Assert.True(einit); Assert.NotNull(elock); Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return(null); })); // Func based initialization without tracking boolean (uninitialized). string f = null; object fLock = null; Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref f, ref fLock, () => strTemplate)); Assert.Equal(strTemplate, f); Assert.NotNull(fLock); // Func based initialization without tracking boolean (already initialized). string g = strTemplate; object gLock = null; Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref g, ref gLock, () => strTemplate + "bar")); Assert.Equal(strTemplate, g); Assert.Null(gLock); // Func based initialization without tracking boolean (nulls not permitted). string h = null; object hLock = null; Assert.Throws <InvalidOperationException>(() => LazyInitializer.EnsureInitialized(ref h, ref hLock, () => null)); }
public InitializeSimpleMembershipAttribute() { LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); }
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return(LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1))); }
public IList <Damage> GetCleanDamages() { return(LazyInitializer.EnsureInitialized(ref _cleanDamages, CalculateCleanDamages)); }
private static string ReadXdgDirectory(string homeDir, string key, string fallback) { Debug.Assert(!string.IsNullOrEmpty(homeDir), $"Expected non-empty homeDir"); Debug.Assert(!string.IsNullOrEmpty(key), $"Expected non-empty key"); Debug.Assert(!string.IsNullOrEmpty(fallback), $"Expected non-empty fallback"); string envPath = GetEnvironmentVariable(key); if (!string.IsNullOrEmpty(envPath) && envPath[0] == '/') { return(envPath); } // Use the user-dirs.dirs file to look up the right config. // Note that the docs also highlight a list of directories in which to look for this file: // "$XDG_CONFIG_DIRS defines the preference-ordered set of base directories to search for configuration files in addition // to the $XDG_CONFIG_HOME base directory. The directories in $XDG_CONFIG_DIRS should be separated with a colon ':'. If // $XDG_CONFIG_DIRS is either not set or empty, a value equal to / etc / xdg should be used." // For simplicity, we don't currently do that. We can add it if/when necessary. string userDirsPath = Path.Combine(GetXdgConfig(homeDir), "user-dirs.dirs"); if (Interop.Sys.Access(userDirsPath, Interop.Sys.AccessMode.R_OK) == 0) { try { // TODO #11151: Replace with direct usage of File.ReadLines or equivalent once we have access to System.IO.FileSystem here. Func <string, IEnumerable <string> > readLines = LazyInitializer.EnsureInitialized(ref s_fileReadLines, () => { Type fileType = Type.GetType("System.IO.File, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); if (fileType != null) { foreach (MethodInfo mi in fileType.GetTypeInfo().GetDeclaredMethods("ReadLines")) { if (mi.GetParameters().Length == 1) { return((Func <string, IEnumerable <string> >)mi.CreateDelegate(typeof(Func <string, IEnumerable <string> >))); } } } return(null); }); IEnumerable <string> lines = readLines?.Invoke(userDirsPath); if (lines != null) { foreach (string line in lines) { // Example lines: // XDG_DESKTOP_DIR="$HOME/Desktop" // XDG_PICTURES_DIR = "/absolute/path" // Skip past whitespace at beginning of line int pos = 0; SkipWhitespace(line, ref pos); if (pos >= line.Length) { continue; } // Skip past requested key name if (string.CompareOrdinal(line, pos, key, 0, key.Length) != 0) { continue; } pos += key.Length; // Skip past whitespace and past '=' SkipWhitespace(line, ref pos); if (pos >= line.Length - 4 || line[pos] != '=') { continue; // 4 for ="" and at least one char between quotes } pos++; // skip past '=' // Skip past whitespace and past first quote SkipWhitespace(line, ref pos); if (pos >= line.Length - 3 || line[pos] != '"') { continue; // 3 for "" and at least one char between quotes } pos++; // skip past opening '"' // Skip past relative prefix if one exists bool relativeToHome = false; const string RelativeToHomePrefix = "$HOME/"; if (string.CompareOrdinal(line, pos, RelativeToHomePrefix, 0, RelativeToHomePrefix.Length) == 0) { relativeToHome = true; pos += RelativeToHomePrefix.Length; } else if (line[pos] != '/') // if not relative to home, must be absolute path { continue; } // Find end of path int endPos = line.IndexOf('"', pos); if (endPos <= pos) { continue; } // Got we need. Now extract it. string path = line.Substring(pos, endPos - pos); return(relativeToHome ? Path.Combine(homeDir, path) : path); } } } catch (Exception exc) { // assembly not found, file not found, errors reading file, etc. Just eat everything. Debug.Fail($"Failed reading {userDirsPath}: {exc}"); } } return(Path.Combine(homeDir, fallback)); }
public virtual void NotifyReaderCreated([NotNull] DbDataReader dataReader) => LazyInitializer .EnsureInitialized( ref _valueBufferFactory, () => QuerySqlGeneratorFactory() .CreateValueBufferFactory(_valueBufferFactoryFactory, dataReader));
public static SerialPort GetInstance() { return(LazyInitializer.EnsureInitialized(ref _instance, () => new SerialPort())); }
public T EnsureInitialized() { return(LazyInitializer.EnsureInitialized <T>(ref _value, ref _initialized, ref _lock, _initializer)); }
void EnsureConsumerInitialized() => LazyInitializer.EnsureInitialized(ref consumer, InitializeConsumer);
internal static T EnsureInitialized <T>(ref T field, Func <T> initializer) where T : class => LazyInitializer.EnsureInitialized(ref field, ref InternalSyncObject, initializer);
public override void OnActionExecuting(ActionExecutingContext filterContext) { // Asegúrese de que ASP.NET Simple Membership se inicialice solo una vez por inicio de la aplicación LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { LazyInitializer.EnsureInitialized(ref membershipInitializer, ref isInitialized, ref initializationLock); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // S'assurer qu'ASP.NET Simple Membership est initialisé une seule fois par démarrage d'application LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); }
private static void EnsureFixedInfo() { LazyInitializer.EnsureInitialized(ref s_fixedInfo, ref s_fixedInfoInitialized, ref s_syncObject, () => GetFixedInfo()); }
/// <summary> /// Returns the machine name. /// </summary> /// <returns>The machine name.</returns> public string GetMachineName() { return(LazyInitializer.EnsureInitialized(ref this.hostName, this.GetHostName)); }
/// <inheritdoc /> public IReadOnlyCollection <ModuleHelpData> GetModuleHelpData() => LazyInitializer.EnsureInitialized(ref _cachedHelpData, () => _commands.Modules .Where(x => !x.Attributes.Any(attr => attr is HiddenFromHelpAttribute)) .Select(x => ModuleHelpData.FromModuleInfo(x)) .ToArray());
/// <summary> /// Initializes a new instance of the <see cref="WebUserSecurity"/> class. /// </summary> /// <param name="securityRepository">The security repository.</param> public WebUserSecurity(ISecurityRepository securityRepository) { _securityRepository = securityRepository; LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); }
/// <summary> /// Resolves type by <paramref name="typeResolver"/> if not yet resoved /// and activates it. /// </summary> /// <param name="typeResolver">Method to resolve type</param> /// <returns></returns> public object Activate(Func <Type> typeResolver) => Activator.CreateInstance(LazyInitializer.EnsureInitialized(ref cache, typeResolver));
public void EnsureInstalled() { LazyInitializer.EnsureInitialized(ref _initDummy, Install); }
public SyncBootState GetSyncBootState() => LazyInitializer.EnsureInitialized( ref _syncBootState, ref _syncBootStateReady, ref _syncBootStateLock, () => InitializeColdBootState(_lastSyncedFileManager.LastSyncedId));
private IProperty[] EnsurePropertiesInitialized() { return(LazyInitializer.EnsureInitialized(ref _properties, LoadProperties)); }
internal IChangeToken GetFilterChangeToken() { CancellationTokenSource cts = LazyInitializer.EnsureInitialized(ref _cancellationTokenSource, () => new CancellationTokenSource()); return(new CancellationChangeToken(cts.Token)); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // Ensure ASP.NET Simple Membership is initialized only once per app start LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); }
public QCTestViewModel() { _model = LazyInitializer.EnsureInitialized <WarehouseModel>(ref _model, () => new WarehouseModel()); }
private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { return(LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1))); }
/// <summary> /// Load settings from the AppSettings section of the config file. /// </summary> /// <returns></returns> public static IDictionary <string, string> LoadFromConfig() { return(LazyInitializer.EnsureInitialized( ref _fromConfigImplementation, () => new FromConfigImplementation())); }