/// <summary>转换多个对象</summary> /// <typeparam name="TInterface"></typeparam> /// <param name="objects"></param> /// <returns></returns> public static TInterface[] Implement <TInterface>(params object[] objects) { if (objects == null) { throw new ArgumentNullException("objects"); } Type interfaceType = typeof(TInterface); ValidateInterfaceType(interfaceType); Type[] duckedTypes = new Type[objects.Length]; for (int i = 0; i < objects.Length; i++) { duckedTypes[i] = objects[i].GetType(); } Type[] duckTypes = GetDuckTypes(interfaceType, duckedTypes); TInterface[] ducks = new TInterface[objects.Length]; for (int i = 0; i < objects.Length; i++) { //ducks[i] = (TInterface)Activator.CreateInstance(duckTypes[i], objects[i]); ducks[i] = (TInterface)TypeX.CreateInstance(duckTypes[i], objects[i]); } return(ducks); }
public TInterface Resolve <TInterface>() { string key = typeof(TInterface).FullName; if (!map.ContainsKey(key)) { throw new Exception(); } Type type = map[key]; #region prepare constructor parameter List <object> parameters = new List <object>(); ConstructorInfo ctor = type.GetConstructors()[0]; // get the 1st one for now foreach (ParameterInfo parameter in ctor.GetParameters()) { Type paraType = parameter.ParameterType; // don't use typeof() here, it will return ParameterInfo string paraKey = paraType.FullName; if (!map.ContainsKey(paraKey)) { throw new Exception(); } Type paraTargetType = map[paraKey]; object pObject = Activator.CreateInstance(paraTargetType); parameters.Add(pObject); } #endregion object o = Activator.CreateInstance(type, parameters.ToArray()); TInterface t = (TInterface)o; return(t); }
/// <summary> /// Returns the type of the first class that implements the specified interface in all loaded assemblies. /// </summary> /// <typeparam name="TInterface"></typeparam> /// <returns></returns> public Sponsor <TInterface> GetImplementation <TInterface>() where TInterface : class { TInterface instance = Builder.GetImplementation <TInterface>(); return(instance != null ? new Sponsor <TInterface>(instance) : null); }
/// <summary> /// Returns new instance of a TInterface implementation. /// </summary> /// <typeparam name="TInterface"></typeparam> /// <returns></returns> public static TInterface Get <TInterface>() where TInterface : class { Func <object> instantiator; Type tInterface = typeof(TInterface); if (!tInterface.IsInterface) { throw new InvalidOperationException(string.Format("\"{0}\" must be an interface.", tInterface)); } lock (interfaceImplementationMap) { interfaceImplementationMap.TryGetValue(tInterface, out instantiator); } if (instantiator == null) { throw new InvalidOperationException("Use Register() before calling Get()."); } TInterface instance = (TInterface)instantiator(); return(instance); }
public async Task <TInterface> RegisterInterface <TInterface>() where TInterface : RegisteredInterface, new() { TInterface devInterface = await this.GetInterface <TInterface>(); Type type = typeof(TInterface); string typeName = type.FullName; if (devInterface != null) { throw new Exception($"DeviceInterface '{typeName}' is already registered"); } var poco = new TInterface() { Name = typeName, }; using (var uow = new UnitOfWork <RegisteredInterface, RomiDbContext>()) { await Task.Run(() => uow.Repository().Add(poco)); } return(await this.GetInterface <TInterface>()); }
public WeakSubscription(WrappedModelBase<TInterface> wrapper) : base(wrapper) { if (wrapper == null) throw new ArgumentNullException(nameof(wrapper)); _ModelInstance = wrapper.ModelInstance; _PropertyChangedEventHandler = ModelInstance_PropertyChanged; }
/// <summary>Get an API for the mod, and show a message if it can't be loaded.</summary> /// <typeparam name="TInterface">The API type.</typeparam> protected TInterface GetValidatedApi <TInterface>() where TInterface : class { TInterface api = this.ModRegistry.GetApi <TInterface>(this.ModID); if (api == null) { this.Monitor.Log($"Detected {this.Label}, but couldn't fetch its API. Data from this mod may not be shown.", LogLevel.Warn); return(null); } return(api); }
/// <summary>Get an API for the mod, and show a message if it can't be loaded.</summary> /// <typeparam name="TInterface">The API type.</typeparam> protected TInterface GetValidatedApi <TInterface>() where TInterface : class { TInterface api = this.ModRegistry.GetApi <TInterface>(this.ModID); if (api == null) { this.Monitor.Log($"Detected {this.Label}, but couldn't fetch its API. Disabled integration with this mod.", LogLevel.Warn); return(null); } return(api); }
public TInterface Resolve <TInterface>() { TInterface tInterface = default(TInterface); object obj; if (_container.TryGetValue(typeof(TInterface).FullName, out obj)) { tInterface = (TInterface)obj; } return(tInterface); }
public static TInterface GetGlobalService <TService, TInterface>() where TInterface : class { if (PackageServiceProvider != null) { TInterface service = PackageServiceProvider.GetService(typeof(TService)) as TInterface; if (service != null) { return(service); } } return((TInterface)Package.GetGlobalService(typeof(TService))); }
/// <summary> /// Gets the default implementation of a given interface. This is what is returned if an /// interface is not implemented for any platform. /// </summary> /// <typeparam name="TInterface">The type of the interface to get.</typeparam> /// <returns>The default interface, as a <typeparamref name="TInterface"/> instance.</returns> /// <exception cref="PlatformNotSupportedException">There is no default implementation of <typeparamref name="TInterface"/>.</exception> public static TInterface GetDefault <TInterface>() where TInterface : class { TInterface iface = QueryDefault <TInterface>(); if (iface == null) { throw new PlatformNotSupportedException(typeof(TInterface)); } return(iface); }
/// <summary> /// Returns the type of the first class that implements the specified interface in all loaded assemblies. /// </summary> /// <typeparam name="TInterface"></typeparam> /// <returns></returns> public Sponsor <TInterface> GetImplementation <TInterface>() where TInterface : class { TInterface instance = Loader.GetImplementation <TInterface>(); if (instance != null) { return(new Sponsor <TInterface>(instance)); } else { return(null); } }
public static async Task <TInterface> GetGlobalServiceFreeThreadedAsync <TService, TInterface>() where TInterface : class { if (PackageServiceProvider != null) { TInterface service = await PackageServiceProvider.GetFreeThreadedServiceAsync <TService, TInterface>(); if (service != null) { return(service); } } return(await AsyncServiceProvider.GlobalProvider.GetServiceAsync <TService, TInterface>()); }
public override TInterface Provide <TInterface>(params object[] args) { TInterface ret = default; var obj = new Object(); lock (obj) { SingletonInjectionDatasetProvider.Make().Set(args[0]); ret = base.Provide <TInterface>(); SingletonInjectionDatasetProvider.Make().Set(null); } return(ret); }
public static TInterface Resolve <TInterface, TModel>() { TInterface ret = default(TInterface); if (_container.IsRegistered(typeof(TInterface))) { ret = _container.Resolve <TInterface>(); } else { _container.RegisterType(typeof(TInterface), typeof(TModel), new TransientLifetimeManager()); ret = _container.Resolve <TInterface>(); } return(ret); }
public static TInterface Resolve <TInterface>() { TInterface result = default(TInterface); try { result = kernel.Get <TInterface>(); } catch (Exception ex) { Debug.WriteLine("could not resolve: " + typeof(TInterface).Name); //System.IO.File.AppendAllText("c:\\IocError.txt",DateTime.Now + " " + nameof(TInterface) + " " + ex.Message); } return(result); }
public static TInterface ResolveOnCurrentInstance <TInterface, TDefault>() where TInterface : class where TDefault : TInterface, new() { TInterface resolved = null; if (Current != null) { resolved = Current.Resolve <TInterface>(); } if (resolved == null) { resolved = new TDefault(); } return(resolved); }
public static TInterface GetSingle <TInterface>() { var t = typeof(TInterface); TInterface result = default(TInterface); object obj = null; if (_singleDic.TryGetValue(t, out obj)) { result = (TInterface)obj; } else { throw new ArgumentException($"未找到 { t.FullName } 实现类!", typeof(TInterface).FullName); } return(result); }
public static Lazy <TInterface> ResolveLazy <TInterface>() { TInterface result = default(TInterface); return(new Lazy <TInterface>(() => { try { result = kernel.Get <TInterface>(); } catch (Exception ex) { Debug.WriteLine("could not resolve: " + typeof(TInterface).Name); } return result; })); }
private static async Task <TInterface> GetGlobalServiceAsync <TService, TInterface>() where TInterface : class { // VS Threading Rule #1 // Access to ServiceProvider and a lot of casts are performed in this method, // and so this method can RPC into main thread. Switch to main thread explictly, since method has STA requirement await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (PackageServiceProvider != null) { var result = PackageServiceProvider.GetService(typeof(TService)); TInterface service = result as TInterface; if (service != null) { return(service); } } return(Package.GetGlobalService(typeof(TService)) as TInterface); }
/// <summary> /// creates an instance of the requested interface. /// </summary> /// <typeparam name="TRepository">The interface of the repository /// to create.</typeparam> /// <typeparam name="TEntity">The type of the Entity that the /// repository is for.</typeparam> /// <returns>An instance of the interface requested.</returns> public static TInterface GetRepository <TInterface>() where TInterface : class { // Initialize the provider's default value TInterface repository = default(TInterface); string interfaceShortName = typeof(TInterface).Name; // Get the UIValidationMappingsConfiguration config section UIValidationSettings settings = (UIValidationSettings)ConfigurationManager.GetSection("ValidationConfiguration"); // Get the type to be created Type repositoryType = null; // See if a valid interfaceShortName was passed in if (settings != null && settings.UIValidationMappings.ContainsKey(interfaceShortName)) { repositoryType = Type.GetType(settings.UIValidationMappings[interfaceShortName].UIValidationFullTypeName); if (repositoryType == null) { throw new ArgumentNullException("خطا در ایجاد انباره. فایل باینری نوع انباره ی درخواست شده یافت نشد" + " Requested Repository Name: " + interfaceShortName); } } // Throw an exception if the right Repository // Mapping Element could not be found and the resulting // Repository Type could not be created if (repositoryType == null) { throw new ArgumentNullException("خطا در ایجاد انباره. نوع انباره ی درخواست شده در فایل تنظیمات یافت نشد" + " Requested Repository Name: " + interfaceShortName); } // Create the repository, and cast it to the interface specified repository = Activator.CreateInstance(repositoryType) as TInterface; return(repository); }
public void OnChange(TInterface options) => _listener.Invoke(options);
public void RegisterSingleton <TInterface, TObject>() where TObject : TInterface { TInterface obj = Create <TObject>(); accessors[typeof(TInterface)] = _ => obj !; }