public IServiceInfo FindService(string serviceAssemblyQualifiedName) { ServiceInfo f; if (_servicesByAssemblyQualifiedName.TryGetValue(serviceAssemblyQualifiedName, out f)) { return(f); } // Second chance: find the assembly (without Version, Culture and PulicKeyToken). string assemblyFullName, fullTypeName; if (SimpleTypeFinder.SplitAssemblyQualifiedName(serviceAssemblyQualifiedName, out fullTypeName, out assemblyFullName)) { PluginAssemblyInfo a = FindAssembly(assemblyFullName); if (a != null) { foreach (var s in a.Services) { if (s.ServiceFullName == fullTypeName) { return(s); } } } } return(null); }
/// <summary> /// Initializes a new <see cref="StObjEngineConfiguration"/> from a <see cref="XElement"/>. /// </summary> /// <param name="e">The xml element.</param> public StObjEngineConfiguration(XElement e) { Throw.CheckNotNullArgument(e); // Global options. BasePath = (string?)e.Element(xBasePath); GeneratedAssemblyName = (string?)e.Element(xGeneratedAssemblyName); TraceDependencySorterInput = (bool?)e.Element(xTraceDependencySorterInput) ?? false; TraceDependencySorterOutput = (bool?)e.Element(xTraceDependencySorterOutput) ?? false; RevertOrderingNames = (bool?)e.Element(xRevertOrderingNames) ?? false; InformationalVersion = (string?)e.Element(xInformationalVersion); var sha1 = (string?)e.Element(xBaseSHA1); BaseSHA1 = sha1 != null?SHA1Value.Parse(sha1) : SHA1Value.Zero; ForceRun = (bool?)e.Element(xForceRun) ?? false; GlobalExcludedTypes = new HashSet <string>(FromXml(e, xGlobalExcludedTypes, xType)); // BinPaths. BinPaths = e.Elements(xBinPaths).Elements(xBinPath).Select(e => new BinPathConfiguration(e)).ToList(); // Aspects. Aspects = new List <IStObjEngineAspectConfiguration>(); foreach (var a in e.Elements(xAspect)) { string type = (string)a.AttributeRequired(xType); Type? tAspect = SimpleTypeFinder.WeakResolver(type, true); Debug.Assert(tAspect != null); IStObjEngineAspectConfiguration aspect = (IStObjEngineAspectConfiguration)Activator.CreateInstance(tAspect, a) !; Aspects.Add(aspect); } }
/// <summary> /// Explicitly registers a set of CK types (<see cref="IPoco"/>, <see cref="IAutoService"/> or <see cref="IRealObject"/>) by their /// assembly qualified names. /// Once the first type is registered, no more call to <see cref="SetAutoServiceKind(Type, AutoServiceKind)"/> is allowed. /// </summary> /// <param name="typeNames">Assembly qualified names of the types to register.</param> public void RegisterTypes(IReadOnlyCollection <string> typeNames) { if (typeNames == null) { throw new ArgumentNullException(nameof(typeNames)); } DoRegisterTypes(typeNames.Select(n => SimpleTypeFinder.WeakResolver(n, true)).Select(t => t !), typeNames.Count); }
int Register(IActivityMonitor monitor, IServiceProvider services, List <Entry> all, MemberInfo m, bool includeBaseClass, IAttributeContextBound[]?alreadyKnownMemberAttributes = null) { int initializerCount = 0; var attr = alreadyKnownMemberAttributes ?? (IAttributeContextBound[])m.GetCustomAttributes(typeof(IAttributeContextBound), includeBaseClass); foreach (var a in attr) { object?finalAttributeToUse = a; if (a is ContextBoundDelegationAttribute delegated) { Type?dT = SimpleTypeFinder.WeakResolver(delegated.ActualAttributeTypeAssemblyQualifiedName, true); Debug.Assert(dT != null); // When ContextBoundDelegationAttribute is not specialized, it is useless: the attribute // parameter must not be specified. using (var sLocal = new SimpleServiceContainer(services)) { Debug.Assert(_all.Length == 0, "Constructors see no attributes at all. IAttributeContextBoundInitializer must be used to have access to other attributes."); sLocal.Add <Type>(Type); sLocal.Add <ITypeAttributesCache>(this); sLocal.Add <MemberInfo>(m); if (m is MethodInfo method) { sLocal.Add <MethodInfo>(method); } else if (m is PropertyInfo property) { sLocal.Add <PropertyInfo>(property); } else if (m is FieldInfo field) { sLocal.Add <FieldInfo>(field); } finalAttributeToUse = a.GetType() == typeof(ContextBoundDelegationAttribute) ? sLocal.SimpleObjectCreate(monitor, dT) : sLocal.SimpleObjectCreate(monitor, dT, a); } if (finalAttributeToUse == null) { continue; } } all.Add(new Entry(m, finalAttributeToUse)); if (finalAttributeToUse is IAttributeContextBoundInitializer) { ++initializerCount; } } return(initializerCount); }
Type MapType(Type t, bool throwOnError) { Debug.Assert(t != typeof(ITestHelperResolvedCallback) && t != typeof(IMixinTestHelper)); string typeName = _config.Get("TestHelper/" + t.FullName); if (typeName != null) { // Always throw when config is used. Type fromConfig = SimpleTypeFinder.WeakResolver(typeName, true); if (typeof(IMixinTestHelper).IsAssignableFrom(fromConfig)) { throw new Exception($"Mapped type '{fromConfig.FullName}' is a Mixin. It can not be explicitely implemented."); } return(fromConfig); } if (t.IsInterface && t.Name[0] == 'I') { var cName = t.Name.Substring(1); string fullName = $"{t.Namespace}.{cName}, {t.Assembly.FullName}"; Type found = SimpleTypeFinder.WeakResolver(fullName, false); if (found == null && cName.EndsWith("Core")) { var nameNoCore = cName.Remove(cName.Length - 4); var ns = t.Namespace.Split('.').ToList(); while (ns.Count > 0) { fullName = $"{String.Join(".", ns)}.{nameNoCore}, {t.Assembly.FullName}"; found = SimpleTypeFinder.WeakResolver(fullName, false); if (found != null) { break; } ns.RemoveAt(ns.Count - 1); } } if (found != null && t.IsAssignableFrom(found)) { return(found); } if (typeof(IMixinTestHelper).IsAssignableFrom(t)) { if (t.GetMembers().Length > 0) { throw new Exception($"Interface '{t.FullName}' is a Mixin. It can not have members of its own."); } return(MixinType.Create(t)); } } if (!throwOnError) { return(null); } throw new Exception($"Unable to locate an implementation for {t.AssemblyQualifiedName}."); }
Type TryResolveType(string name) { Type resolved; if (name.IndexOf(',') >= 0) { // It must be an assembly qualified name. // Weaken its name and try to load it. // If it fails and the name does not end with "Configuration" tries it. string fullTypeName, assemblyFullName, assemblyName, versionCultureAndPublicKeyToken; if (SimpleTypeFinder.SplitAssemblyQualifiedName(name, out fullTypeName, out assemblyFullName) && SimpleTypeFinder.SplitAssemblyFullName(assemblyFullName, out assemblyName, out versionCultureAndPublicKeyToken)) { var weakTypeName = fullTypeName + ", " + assemblyName; resolved = SimpleTypeFinder.RawGetType(weakTypeName, false); if (resolved != null) { return(IsHandlerConfiguration(resolved)); } if (!fullTypeName.EndsWith("Configuration")) { weakTypeName = fullTypeName + "Configuration, " + assemblyName; resolved = SimpleTypeFinder.RawGetType(weakTypeName, false); if (resolved != null) { return(IsHandlerConfiguration(resolved)); } } } return(null); } // This is a simple type name: try to find the type name in already loaded assemblies. var configTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .Where(t => typeof(IHandlerConfiguration).IsAssignableFrom(t)) .ToList(); var nameWithC = !name.EndsWith("Configuration") ? name + "Configuration" : null; if (name.IndexOf('.') > 0) { // It is a FullName. resolved = configTypes.FirstOrDefault(t => t.FullName == name || (nameWithC != null && t.FullName == nameWithC)); } else { // There is no dot in the name. resolved = configTypes.FirstOrDefault(t => t.Name == name || (nameWithC != null && t.Name == nameWithC)); } return(resolved); }
PluginAssemblyInfo FindAssembly(string assemblyFullName) { string assemblyName, versionCultureAndPublicKeyToken; if (SimpleTypeFinder.SplitAssemblyFullName(assemblyFullName, out assemblyName, out versionCultureAndPublicKeyToken)) { foreach (var a in _allAssemblies) { if (a.AssemblyName.Name == assemblyName) { return(a); } } } return(null); }
bool IStObjTypeFilter.TypeFilter(IActivityMonitor monitor, Type t) { // Type.FullName is null if the current instance represents a generic type parameter, an array // type, pointer type, or byref type based on a type parameter, or a generic type // that is not a generic type definition but contains unresolved type parameters. // This FullName is also null for (at least) classes nested into nested generic classes. // In all cases, we emit a warn and filters this beast out. if (t.FullName == null) { monitor.Warn($"Type has no FullName: '{t.Name}'. It is excluded."); return(false); } Debug.Assert(t.AssemblyQualifiedName != null, "Since FullName is defined."); if (_excludedTypes.Contains(t.Name)) { monitor.Info($"Type {t.AssemblyQualifiedName} is filtered out by its Type Name."); return(false); } if (_excludedTypes.Contains(t.FullName)) { monitor.Info($"Type {t.AssemblyQualifiedName} is filtered out by its Type FullName."); return(false); } if (_excludedTypes.Contains(t.AssemblyQualifiedName)) { monitor.Info($"Type {t.AssemblyQualifiedName} is filtered out by its Type AssemblyQualifiedName."); return(false); } if (SimpleTypeFinder.WeakenAssemblyQualifiedName(t.AssemblyQualifiedName, out var weaken) && _excludedTypes.Contains(weaken)) { monitor.Info($"Type {t.AssemblyQualifiedName} is filtered out by its weak type name ({weaken})."); return(false); } // We only care about IPoco and IRealObject. Nothing more. if (_isUnifiedPure) { if (!typeof(IPoco).IsAssignableFrom(t) && !typeof(IRealObject).IsAssignableFrom(t)) { return(false); } } return(_firstLayer?.TypeFilter(monitor, t) ?? true); }
/// <summary> /// Sets <see cref="AutoServiceKind"/> combination for a type: the type is always resolved (<see cref="SimpleTypeFinder.WeakResolver"/>). /// Can be called multiple times as long as no contradictory registration already exists (for instance, a <see cref="IRealObject"/> /// cannot be a Front service). /// </summary> /// <param name="typeName">The assembly qualified type name to register.</param> /// <param name="kind">The kind of service. Can be <see cref="AutoServiceKind.None"/> (nothing is done except the type resolution).</param> /// <param name="isOptional">True to warn if the type is not found instead of logging an error and returning false.</param> /// <returns>True on success, false on error.</returns> public bool SetAutoServiceKind(string typeName, AutoServiceKind kind, bool isOptional) { if (String.IsNullOrWhiteSpace(typeName)) { throw new ArgumentNullException(nameof(typeName)); } var t = SimpleTypeFinder.WeakResolver(typeName, false); if (t != null) { return(kind != AutoServiceKind.None ? SetAutoServiceKind(t, kind) : true); } if (isOptional) { _monitor.Warn($"Type name '{typeName}' not found. It is ignored (SetAutoServiceKind: {kind})."); return(true); } ++_registerFatalOrErrorCount; _monitor.Error($"Unable to resolve expected type named '{typeName}' (SetAutoServiceKind: {kind})."); return(false); }
static Type FindConfigurationType(string type) { Type t = SimpleTypeFinder.WeakResolver(type, false); if (t == null) { string fullTypeName, assemblyFullName; if (!SimpleTypeFinder.SplitAssemblyQualifiedName(type, out fullTypeName, out assemblyFullName)) { fullTypeName = type; assemblyFullName = "CK.Monitoring"; } if (!fullTypeName.EndsWith("Configuration")) { fullTypeName += "Configuration"; } t = SimpleTypeFinder.WeakResolver(fullTypeName + ", " + assemblyFullName, false); if (t == null) { t = SimpleTypeFinder.WeakResolver("CK.Monitoring.GrandOutputHandlers." + fullTypeName + ", " + assemblyFullName, true); } } return(t); }