Here are the examples of the csharp api System.IServiceProvider.GetService(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2827 Examples
19
Source : Reader.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static Reader<TService> GetService<TService>() =>
Reader<TService>.Read<IServiceProvider>(serviceProvider => (TService)serviceProvider.GetService(typeof(TService)));
19
Source : PollyCircuitBreaker.cs
with MIT License
from 1100100
with MIT License
from 1100100
private AsyncPolicy<IServiceResult> GetPolicy(string route, Type returnValueType)
{
return Policies.GetOrAdd(route, key =>
{
var service = ServiceFactory.Get(route);
var serviceCircuitBreakerOptions = service.ServiceCircuitBreakerOptions;
var circuitBreakerEvent = ServiceProvider.GetService<ICircuitBreakerEvent>();
AsyncPolicy<IServiceResult> policy = Policy<IServiceResult>.Handle<Exception>().FallbackAsync<IServiceResult>(
async ct =>
{
//TODO 如果多次降级,根据路由排除此node
if (circuitBreakerEvent != null)
await circuitBreakerEvent.OnFallback(route, service.ClientMethodInfo);
if (returnValueType == null)
return new ServiceResult(null);
if (service.ServiceCircuitBreakerOptions.HasInjection)
return new ServiceResult(await ScriptInjection.Run(route));
return new ServiceResult(returnValueType.IsValueType ? Activator.CreateInstance(returnValueType) : default);
});
if (serviceCircuitBreakerOptions.ExceptionsAllowedBeforeBreaking > 0)
{
policy = policy.WrapAsync(Policy.Handle<Exception>().CircuitBreakerAsync(serviceCircuitBreakerOptions.ExceptionsAllowedBeforeBreaking, serviceCircuitBreakerOptions.DurationOfBreak,
async (ex, state, ts, ctx) =>
{
if (circuitBreakerEvent != null)
await circuitBreakerEvent.OnBreak(route, service.ClientMethodInfo, ex, ts);
},
async ctx =>
{
if (circuitBreakerEvent != null)
await circuitBreakerEvent.OnRest(route, service.ClientMethodInfo);
},
async () =>
{
if (circuitBreakerEvent != null)
await circuitBreakerEvent.OnHalfOpen(route, service.ClientMethodInfo);
}));
}
if (serviceCircuitBreakerOptions.Retry > 0)
{
policy = policy.WrapAsync(Policy.Handle<Exception>().RetryAsync(serviceCircuitBreakerOptions.Retry,
async (ex, times) =>
{
if (circuitBreakerEvent != null)
await circuitBreakerEvent.OnRetry(route, service.ClientMethodInfo, ex, times);
}));
}
if (serviceCircuitBreakerOptions.MaxParallelization > 0)
{
policy = policy.WrapAsync(Policy.BulkheadAsync(serviceCircuitBreakerOptions.MaxParallelization, serviceCircuitBreakerOptions.MaxQueuingActions, async ctx =>
{
if (circuitBreakerEvent != null)
await circuitBreakerEvent.OnBulkheadRejected(route, service.ClientMethodInfo);
}));
}
if (serviceCircuitBreakerOptions.Timeout.Ticks > 0)
{
policy = policy.WrapAsync(Policy.TimeoutAsync(serviceCircuitBreakerOptions.Timeout, TimeoutStrategy.Pessimistic,
async (ctx, ts, task, ex) =>
{
if (circuitBreakerEvent != null)
await circuitBreakerEvent.OnTimeOut(route, service.ClientMethodInfo, ex);
}));
}
return policy;
});
}
19
Source : ServiceBuilder.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task StartAsync(CancellationToken cancellationToken)
{
UraganoSettings.ClientGlobalInterceptors.Reverse();
UraganoSettings.ServerGlobalInterceptors.Reverse();
var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
var enableServer = UraganoSettings.ServerSettings != null;
var types = ReflectHelper.GetDependencyTypes();
var services = types.Where(t => t.IsInterface && typeof(IService).IsreplacedignableFrom(t)).Select(@interface => new
{
Interface = @interface,
Implementation = types.FirstOrDefault(p => p.IsClreplaced && p.IsPublic && !p.IsAbstract && !p.Name.EndsWith("_____UraganoClientProxy") && @interface.IsreplacedignableFrom(p))
}).ToList();
foreach (var service in services)
{
var imp = service.Implementation;
var routeAttr = service.Interface.GetCustomAttribute<ServiceRouteAttribute>();
var routePrefix = routeAttr == null ? $"{service.Interface.Namespace}/{service.Interface.Name}" : routeAttr.Route;
var interfaceMethods = service.Interface.GetMethods();
List<MethodInfo> implementationMethods = null;
if (enableServer && imp != null)
implementationMethods = imp.GetMethods().ToList();
var disableClientIntercept = service.Interface.GetCustomAttribute<NonInterceptAttribute>(true) != null;
var clientClreplacedInterceptors = new List<Type>();
if (!disableClientIntercept)
clientClreplacedInterceptors = service.Interface.GetCustomAttributes(true).Where(p => p is IInterceptor)
.Select(p => p.GetType()).ToList();
var serverClreplacedInterceptors = new List<Type>();
var disableServerIntercept = false;
if (enableServer && imp != null)
{
disableServerIntercept = imp.GetCustomAttribute<NonInterceptAttribute>(true) != null;
if (!disableServerIntercept)
serverClreplacedInterceptors = imp.GetCustomAttributes(true).Where(p => p is IInterceptor)
.Select(p => p.GetType()).ToList();
}
foreach (var interfaceMethod in interfaceMethods)
{
MethodInfo serverMethod = null;
var idAttr = interfaceMethod.GetCustomAttribute<ServiceRouteAttribute>();
var route = idAttr == null ? $"{routePrefix}/{interfaceMethod.Name}" : $"{routePrefix}/{idAttr.Route}";
var clientInterceptors = new List<Type>();
if (enableClient && !disableClientIntercept && interfaceMethod.GetCustomAttribute<NonInterceptAttribute>(true) == null)
{
clientInterceptors.AddRange(UraganoSettings.ClientGlobalInterceptors);
clientInterceptors.AddRange(clientClreplacedInterceptors);
clientInterceptors.AddRange(interfaceMethod.GetCustomAttributes(true)
.Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
clientInterceptors.Reverse();
}
var serverInterceptors = new List<Type>();
if (enableServer && imp != null)
{
serverMethod = implementationMethods.First(p => IsImplementationMethod(interfaceMethod, p));
if (!disableServerIntercept && serverMethod?.GetCustomAttribute<NonInterceptAttribute>(true) == null)
{
serverInterceptors.AddRange(UraganoSettings.ServerGlobalInterceptors);
serverInterceptors.AddRange(serverClreplacedInterceptors.ToList());
if (serverMethod != null)
serverInterceptors.AddRange(serverMethod.GetCustomAttributes(true)
.Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
serverInterceptors.Reverse();
}
}
ServiceFactory.Create(route, serverMethod, interfaceMethod, serverInterceptors, clientInterceptors);
}
}
await Task.CompletedTask;
}
19
Source : ServiceFactory.cs
with MIT License
from 1100100
with MIT License
from 1100100
public void Create(string route, MethodInfo serverMethodInfo, MethodInfo clientMethodInfo, List<Type> serverInterceptors, List<Type> clientInterceptors)
{
if (ServiceInvokers.ContainsKey(route))
throw new DuplicateRouteException(route);
var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
ServiceCircuitBreakerOptions breaker = null;
CachingConfig cachingConfig = null;
if (enableClient)
{
#region Circuit breaker
var nonCircuitBreakerAttr = clientMethodInfo.GetCustomAttribute<NonCircuitBreakerAttribute>();
if (nonCircuitBreakerAttr == null)
{
var circuitBreakerAttr = clientMethodInfo.GetCustomAttribute<CircuitBreakerAttribute>();
var globalCircuitBreaker = UraganoSettings.CircuitBreakerOptions;
if (globalCircuitBreaker != null || circuitBreakerAttr != null)
{
breaker = new ServiceCircuitBreakerOptions();
if (globalCircuitBreaker != null)
{
breaker.Timeout = globalCircuitBreaker.Timeout;
breaker.Retry = globalCircuitBreaker.Retry;
breaker.ExceptionsAllowedBeforeBreaking =
globalCircuitBreaker.ExceptionsAllowedBeforeBreaking;
breaker.DurationOfBreak = globalCircuitBreaker.DurationOfBreak;
breaker.MaxParallelization = globalCircuitBreaker.MaxParallelization;
breaker.MaxQueuingActions = globalCircuitBreaker.MaxQueuingActions;
}
if (circuitBreakerAttr != null)
{
if (circuitBreakerAttr.TimeoutMilliseconds > -1)
breaker.Timeout = TimeSpan.FromMilliseconds(circuitBreakerAttr.TimeoutMilliseconds);
if (circuitBreakerAttr.Retry > -1)
breaker.Retry = circuitBreakerAttr.Retry;
if (circuitBreakerAttr.ExceptionsAllowedBeforeBreaking > -1)
breaker.ExceptionsAllowedBeforeBreaking =
circuitBreakerAttr.ExceptionsAllowedBeforeBreaking;
if (circuitBreakerAttr.DurationOfBreakSeconds > -1)
breaker.DurationOfBreak = TimeSpan.FromSeconds(circuitBreakerAttr.DurationOfBreakSeconds);
if (!string.IsNullOrWhiteSpace(circuitBreakerAttr.FallbackExecuteScript))
{
breaker.HasInjection = true;
ScriptInjection.AddScript(route, circuitBreakerAttr.FallbackExecuteScript,
circuitBreakerAttr.ScriptUsingNameSpaces);
}
if (circuitBreakerAttr.MaxParallelization > -1)
breaker.MaxParallelization = circuitBreakerAttr.MaxParallelization;
if (circuitBreakerAttr.MaxQueuingActions > -1)
breaker.MaxQueuingActions = circuitBreakerAttr.MaxQueuingActions;
}
}
}
#endregion
#region Caching
//Must have a method of returning a value.
if (UraganoSettings.CachingOptions != null && clientMethodInfo.ReturnType != typeof(Task) && clientMethodInfo.GetCustomAttribute<NonCachingAttribute>() == null && clientMethodInfo.DeclaringType?.GetCustomAttribute<NonCachingAttribute>() == null)
{
var attr = clientMethodInfo.GetCustomAttribute<CachingAttribute>();
var keyGenerator = ServiceProvider.GetRequiredService<ICachingKeyGenerator>();
var key = keyGenerator.GenerateKeyPlaceholder(UraganoSettings.CachingOptions.KeyPrefix, UraganoSettings.CachingOptions.ExpireSeconds, route, clientMethodInfo, attr);
cachingConfig = new CachingConfig(key, attr != null && !string.IsNullOrWhiteSpace(attr.Key), attr != null && attr.ExpireSeconds != -1 ? attr.ExpireSeconds : UraganoSettings.CachingOptions.ExpireSeconds);
}
#endregion
}
var serviceDescriptor = new ServiceDescriptor(route, serverMethodInfo, clientMethodInfo, serverMethodInfo == null ? null : new MethodInvoker(serverMethodInfo), serverInterceptors, clientInterceptors, breaker, cachingConfig);
ServiceInvokers.TryAdd(route, serviceDescriptor);
}
19
Source : DependencyInjection.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static TService Get<TService>(this IServiceProvider provider)
{
return (TService)provider.GetService(typeof(TService));
}
19
Source : ViewSourceControlHistoryCommand.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private void MenuItemCallback(object sender, EventArgs e)
{
// ThreadHelper.ThrowIfNotOnUIThread();
var uiShell = (IVsUIShell)ServiceProvider.GetService(typeof(SVsUIShell));
if (uiShell == null)
{
MessageHelper.ShowMessage("Internal error: uiShell is null");
return;
}
try
{
uiShell.SetWaitCursor();
switch ((uint)((MenuCommand)sender).CommandID.ID)
{
case PkgCmdIDList.CmdSitronicsVisualizeHistory:
if (TeamExplorerIntegrator != null)
TeamExplorerIntegrator.ViewHistory();
break;
}
}
catch (Exception ex)
{
MessageHelper.ShowShellErrorMessage(uiShell, ex);
}
}
19
Source : Program.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public async Task RunBotAsync(string botToken)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
_discordClient = new DiscordSocketClient();
_commands = new CommandService();
var optionsBuilder = new DbContextOptionsBuilder<BotDataContext>();
var options = optionsBuilder
.UseSqlite(PathToDb)
.Options;
var services = new ServiceCollection()
.AddSingleton<DiscordSocketClient>(_discordClient)
.AddSingleton<ApplicationContext>()
.AddSingleton<BotDataContext>(new BotDataContext(options))
.AddSingleton<CommandService>(_commands)
.AddSingleton<OCUserRepository>()
.AddSingleton<Chanel2ServerRepository>()
.AddSingleton<DiscordManager>()
.AddSingleton<IRepository<OCUser>>(x => x.GetService<OCUserRepository>())
.AddSingleton<IRepository<Chanel2Server>>(x => x.GetService<Chanel2ServerRepository>());
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
if (!type.IsClreplaced)
{
continue;
}
if (type.GetInterfaces().Any(x => x == typeof(ICommand)))
{
services.AddSingleton(type);
}
}
_services = services
.AddSingleton<Listener>()
.BuildServiceProvider();
_discordClient.Log += _discordClient_Log;
_discordClient.ChannelDestroyed += _discordClient_ChannelDestroyed;
await RegisterCommandAsync();
await _discordClient.LoginAsync(Discord.TokenType.Bot, botToken);
await _discordClient.StartAsync();
var listener = _services.GetService<Listener>();
const int WAIT_LOGIN_DISCORD_TIME = 5000;
const int REFRESH_TIME = 5000;
var t = new System.Threading.Timer((a) => { listener.UpdateChats(); }, null, WAIT_LOGIN_DISCORD_TIME, REFRESH_TIME);
await Task.Delay(-1);
}
19
Source : Program.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private Task _discordClient_ChannelDestroyed(SocketChannel channel)
{
var cmd = _services.GetService<DiscordManager>();
cmd.ChannelDestroyedCommand(channel.Id);
return Task.CompletedTask;
}
19
Source : TextDocument.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
object IServiceProvider.GetService(Type serviceType)
{
return this.ServiceProvider.GetService(serviceType);
}
19
Source : ThemeUpdater.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private void VSColorTheme_ThemeChanged(ThemeChangedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (_clreplacedificationFormatMapService == null || _clreplacedificationRegistry == null)
{
var componentModel = _serviceProvider.GetService<SComponentModel, IComponentModel>();
_clreplacedificationFormatMapService ??= componentModel?.GetService<IClreplacedificationFormatMapService>();
_clreplacedificationRegistry ??= componentModel?.GetService<IClreplacedificationTypeRegistryService>();
}
if (_clreplacedificationFormatMapService == null || _clreplacedificationRegistry == null)
return;
var logger = AreplacedinatorVSPackage.Instance?.AreplacedinatorLogger;
_fontAndColorStorage ??= _serviceProvider.GetService<SVsFontAndColorStorage, IVsFontAndColorStorage>();
_fontAndColorCacheManager ??= _serviceProvider.GetService<SVsFontAndColorCacheManager, IVsFontAndColorCacheManager>();
IClreplacedificationFormatMap formatMap = _clreplacedificationFormatMapService.GetClreplacedificationFormatMap(category: TextCategory);
if (_fontAndColorStorage == null || _fontAndColorCacheManager == null || formatMap == null)
return;
_fontAndColorCacheManager.CheckCache(ref _mefItemsGuid, out int _);
int openCategoryResult = _fontAndColorStorage.OpenCategory(ref _mefItemsGuid, (uint)__FCSTORAGEFLAGS.FCSF_READONLY);
if (openCategoryResult != VSConstants.S_OK)
{
logger?.LogMessage($"Error on opening category in the registry during the theme change. The error code is {openCategoryResult}", Logger.LogMode.Error);
}
try
{
var areplacedinatorThemeChangedEventArgs = new AreplacedinatorThemeChangedEventArgs(_fontAndColorStorage, _clreplacedificationRegistry, formatMap);
formatMap.BeginBatchUpdate();
AreplacedinatorThemeChanged?.Invoke(this, areplacedinatorThemeChangedEventArgs);
}
catch (Exception exception)
{
logger?.LogException(exception, logOnlyFromAreplacedinatorreplacedemblies: false, Logger.LogMode.Error);
}
finally
{
formatMap.EndBatchUpdate();
int refreshCacheResult = _fontAndColorCacheManager.RefreshCache(ref _mefItemsGuid);
if (refreshCacheResult != VSConstants.S_OK)
{
logger?.LogMessage($"Error on the refresh of MEF Items cache in the registry during the theme change. The error code is {refreshCacheResult}", Logger.LogMode.Error);
}
_fontAndColorStorage.CloseCategory();
}
}
19
Source : RabbitMqInitHost.cs
with MIT License
from ad313
with MIT License
from ad313
private object GetInstance(IServiceProvider serviceProvider, Type type)
{
return serviceProvider.GetService(type) ?? ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, type);
}
19
Source : VSServicesExtensions.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static TService GetService<TService>(this IServiceProvider serviceProvider)
where TService : clreplaced
{
return serviceProvider?.GetService(typeof(TService)) as TService;
}
19
Source : VSServicesExtensions.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static TActual GetService<TRequested, TActual>(this IServiceProvider serviceProvider)
where TRequested : clreplaced
where TActual : clreplaced
{
return serviceProvider?.GetService(typeof(TRequested)) as TActual;
}
19
Source : AopCacheProviderInstance.cs
with MIT License
from ad313
with MIT License
from ad313
private static void Init()
{
if (ServiceProvider == null)
throw new ArgumentNullException(nameof(ServiceProvider));
_aopCacheProvider ??= ServiceProvider.GetService<IAopCacheProvider>();
}
19
Source : TestBase.cs
with MIT License
from ad313
with MIT License
from ad313
protected T GetService<T>()
{
return ServiceProvider.GetService<T>();
}
19
Source : EntityRightsViewDesigner.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override string GetEditableDesignerRegionContent(EditableDesignerRegion region)
{
if (region is EnreplacedyRightsViewDesignerRegion)
{
var template = ((EnreplacedyRightsViewDesignerRegion)region).Template;
if (template != null)
{
var service = (IDesignerHost)Component.Site.GetService(typeof(IDesignerHost));
return ControlPersister.PersistTemplate(template, service);
}
}
return base.GetEditableDesignerRegionContent(region);
}
19
Source : EntityRightsViewDesigner.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void SetEditableDesignerRegionContent(EditableDesignerRegion region, string content)
{
var region2 = region as EnreplacedyRightsViewDesignerRegion;
if (region2 == null) return;
var service = (IDesignerHost)Component.Site.GetService(typeof(IDesignerHost));
var template = ControlParser.ParseTemplate(service, content);
using (var transaction = service.CreateTransaction("SetEditableDesignerRegionContent"))
{
region2.PropertyDescriptor.SetValue(region2.Object, template);
transaction.Commit();
}
region2.Template = template;
}
19
Source : CoreAElfModule.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static IEnumerable<T> GetServices<T>(this IServiceProvider provider, IEnumerable<Type> types)
{
return types.Select(type => (T) provider.GetService(type));
}
19
Source : ITaskQueue.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public ITaskQueue CreateQueue(string name, int maxDegreeOfParallelism)
{
var q = _serviceProvider.GetService<ITaskQueue>();
q.Start(maxDegreeOfParallelism);
if (!_taskQueues.TryAdd(name, q))
{
throw new InvalidOperationException("queue already created");
}
return q;
}
19
Source : HostSmartContractBridgeContextService.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public IHostSmartContractBridgeContext Create()
{
//Create a new context
var context = _serviceProvider.GetService<IHostSmartContractBridgeContext>();
return context;
}
19
Source : IocHelper.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static TInterface Create<TInterface>()
where TInterface : clreplaced
{
return ServiceProvider.GetService<TInterface>();
}
19
Source : IocHelper.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static TInterface CreateBut<TInterface, TDefault>()
where TInterface : clreplaced
where TDefault : clreplaced, TInterface, new()
{
return ServiceProvider.GetService<TInterface>() ?? new TDefault();
}
19
Source : NetCoreKeyedComponentResolver.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
public T Resolve(string key)
{
if (!_registrations.TryGetValue(key, out var implementationType))
throw new ArgumentException($"Service name '{key}' is not registered");
return (T)_container.GetService(implementationType);
}
19
Source : StartupExtension.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
public T Resolve<T>()
{
return _serviceProvider.GetService<T>();
}
19
Source : DynamicAuthenticationBuilderExtensions.cs
with MIT License
from Aguafrommars
with MIT License
from Aguafrommars
private static RedisLogger CreateLogger(IServiceProvider provider)
{
var logger = provider.GetService<ILogger<RedisLogger>>();
var redisLogger = logger != null ? new RedisLogger(logger) : null;
return redisLogger;
}
19
Source : CommandsNextUtilities.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
internal static object CreateInstance(this Type t, IServiceProvider services)
{
var ti = t.GetTypeInfo();
var constructors = ti.DeclaredConstructors
.Where(xci => xci.IsPublic)
.ToArray();
if (constructors.Length != 1)
throw new ArgumentException("Specified type does not contain a public constructor or contains more than one public constructor.");
var constructor = constructors[0];
var constructorArgs = constructor.GetParameters();
var args = new object[constructorArgs.Length];
if (constructorArgs.Length != 0 && services == null)
throw new InvalidOperationException("Dependency collection needs to be specified for parameterized constructors.");
// inject via constructor
if (constructorArgs.Length != 0)
for (var i = 0; i < args.Length; i++)
args[i] = services.GetRequiredService(constructorArgs[i].ParameterType);
var moduleInstance = Activator.CreateInstance(t, args);
// inject into properties
var props = t.GetRuntimeProperties().Where(xp => xp.CanWrite && xp.SetMethod != null && !xp.SetMethod.IsStatic && xp.SetMethod.IsPublic);
foreach (var prop in props)
{
if (prop.GetCustomAttribute<DontInjectAttribute>() != null)
continue;
var service = services.GetService(prop.PropertyType);
if (service == null)
continue;
prop.SetValue(moduleInstance, service);
}
// inject into fields
var fields = t.GetRuntimeFields().Where(xf => !xf.IsInitOnly && !xf.IsStatic && xf.IsPublic);
foreach (var field in fields)
{
if (field.GetCustomAttribute<DontInjectAttribute>() != null)
continue;
var service = services.GetService(field.FieldType);
if (service == null)
continue;
field.SetValue(moduleInstance, service);
}
return moduleInstance;
}
19
Source : AutowiredControllerActivator.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
private object CreateInstance(IServiceProvider serviceProvider, Type type, int deep = 1)
{
// 超过指定深度,返回null
if (deep > MaxDeep)
{
return null;
}
var instance = serviceProvider.GetService(type);
// 当实例可以从容器中获取时,继续在实例中寻找可以自动注入的对象
if (instance != null)
{
// 在类型中查找
var autowiredFields = instance.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
// 循环创建实例
foreach (var field in autowiredFields)
{
var fieldInstance = CreateInstance(serviceProvider, field.FieldType, deep + 1);
// 如果实例可以获得,并且其包含自动装配特性,则将其放入字段中
if (fieldInstance != null &&
field.GetCustomAttribute<AutowiredAttribute>() != null)
{
field.SetValue(instance, fieldInstance);
}
}
}
return instance;
}
19
Source : ExportersManager.cs
with MIT License
from akpaevj
with MIT License
from akpaevj
private void StartExporter(string path, string name, string dataBaseName)
{
var logFolder = Path.Combine(path, "1Cv8Log");
// Check this is an old event log format
var lgfPath = Path.Combine(logFolder, "1Cv8.lgf");
var needStart = File.Exists(lgfPath);
if (needStart)
{
lock (_runExporters)
{
if (!_runExporters.ContainsKey(path))
{
var cts = new CancellationTokenSource();
var logger =
(ILogger<EventLogExporter>) _serviceProvider.GetService(typeof(ILogger<EventLogExporter>));
var storage = GetStorage(dataBaseName);
var settings = new EventLogExporterSettings
{
LogFolder = logFolder,
CollectedFactor = _collectedFactor,
LoadArchive = _loadArchive,
Portion = _portion,
ReadingTimeout = _readingTimeout,
TimeZone = _timeZone,
WritingMaxDop = _writingMaxDop
};
var exporter = new EventLogExporter(settings, storage, logger);
Task.Factory.StartNew(async () =>
{
try
{
await exporter.StartAsync(cts.Token);
}
catch (TaskCanceledException)
{
}
catch (Exception ex)
{
_logger?.LogCritical(ex, "Failed to execute EventLogExporter");
}
}, cts.Token);
_runExporters.Add(path, cts);
_logger?.LogInformation(
$"Event log exporter for \"{name}\" information base to \"{dataBaseName}\" is started");
}
}
}
else
{
_logger?.LogInformation(
$"Event log of \"{name}\" information base is in \"new\" format, it won't be handled");
}
}
19
Source : ExportersManager.cs
with MIT License
from akpaevj
with MIT License
from akpaevj
private IEventLogStorage GetStorage(string dataBaseName)
{
switch (_storageType)
{
case StorageType.ClickHouse:
{
var logger =
(ILogger<ClickHouseStorage>) _serviceProvider.GetService(typeof(ILogger<ClickHouseStorage>));
var connectionString = $"{_connectionString}Database={dataBaseName};";
return new ClickHouseStorage(connectionString, logger);
}
case StorageType.ElasticSearch:
{
var logger =
(ILogger<ElasticSearchStorage>) _serviceProvider.GetService(
typeof(ILogger<ElasticSearchStorage>));
var settings = new ElasticSearchStorageSettings
{
Index = dataBaseName,
Separation = _separation,
MaximumRetries = _maximumRetries,
MaxRetryTimeout = _maxRetryTimeout
};
settings.Nodes.AddRange(_nodes);
return new ElasticSearchStorage(settings, logger);
}
case StorageType.None:
throw new Exception("StorageType parameter is not specified");
default:
throw new Exception("Try to get a storage for unknown StorageType value");
}
}
19
Source : SourceView.cs
with GNU General Public License v2.0
from albertogeniola
with GNU General Public License v2.0
from albertogeniola
private void button3_Click(object sender, EventArgs e)
{
IDtsVariableService vservice = (IDtsVariableService)_sp.GetService(typeof(IDtsVariableService));
Microsoft.SqlServer.Dts.Runtime.Variable vv = vservice.PromptAndCreateVariable(this, null, "COOKIES_" + this.Name, "User", typeof(object));
if (vv != null)
{
cookieVarTb.Text = vv.QualifiedName;
}
}
19
Source : SourceView.cs
with GNU General Public License v2.0
from albertogeniola
with GNU General Public License v2.0
from albertogeniola
private void addButton_Click(object sender, EventArgs e)
{
if (variableR.Checked)
{
IDtsVariableService vservice = (IDtsVariableService)_sp.GetService(typeof(IDtsVariableService));
Microsoft.SqlServer.Dts.Runtime.Variable vv = vservice.PromptAndCreateVariable(this, null, null, "User", typeof(string));
if (vv != null)
uiWebURL.Text = vv.QualifiedName;
}
}
19
Source : AspNetCoreJobActivator.cs
with MIT License
from albyho
with MIT License
from albyho
public virtual object ActivateJob(Type jobType)
{
return _applicationServices.GetService(jobType);
}
19
Source : Startup.cs
with MIT License
from albyho
with MIT License
from albyho
private void ConfigureSenparc(IApplicationBuilder app, IRouteBuilder routes, IServiceProvider serviceProvider)
{
// 获取服务
var env = serviceProvider.GetService<Microsoft.AspNetCore.Hosting.IHostingEnvironment>();
var senparcSetting = serviceProvider.GetService<IOptions<SenparcSetting>>().Value;
var senparcWeixinSetting = serviceProvider.GetService<IOptions<SenparcWeixinSetting>>().Value;
// 启动 CO2NET 全局注册,必须!
var register = RegisterService.Start(env, senparcSetting)
//关于 UseSenparcGlobal() 的更多用法见 CO2NET Demo:https://github.com/Senparc/Senparc.CO2NET/blob/master/Sample/Senparc.CO2NET.Sample.netcore/Startup.cs
.UseSenparcGlobal();
#region CO2NET 全局配置
#region 全局缓存配置(按需)
//当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须)
register.ChangeDefaultCacheNamespace("DefaultCO2NETCache");
#region 配置和使用 Redis
//配置全局使用Redis缓存(按需,独立)
var redisConfigurationStr = senparcSetting.Cache_Redis_Configuration;
var useRedis = !string.IsNullOrEmpty(redisConfigurationStr) && redisConfigurationStr != "#{Cache_Redis_Configuration}#"/*默认值,不启用*/;
if (useRedis)//这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的,这里的if条件可以忽略
{
/* 说明:
* 1、Redis 的连接字符串信息会从 Config.SenparcSetting.Cache_Redis_Configuration 自动获取并注册,如不需要修改,下方方法可以忽略
/* 2、如需手动修改,可以通过下方 SetConfigurationOption 方法手动设置 Redis 链接信息(仅修改配置,不立即启用)
*/
Senparc.CO2NET.Cache.Redis.Register.SetConfigurationOption(redisConfigurationStr);
//以下会立即将全局缓存设置为 Redis
Senparc.CO2NET.Cache.Redis.Register.UseKeyValueRedisNow();//键值对缓存策略(推荐)
//Senparc.CO2NET.Cache.Redis.Register.UseHashRedisNow();//HashSet储存格式的缓存策略
//也可以通过以下方式自定义当前需要启用的缓存策略
//CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);//键值对
//CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisHashSetObjectCacheStrategy.Instance);//HashSet
}
//如果这里不进行Redis缓存启用,则目前还是默认使用内存缓存
#endregion
#endregion
Senparc.CO2NET.APM.Config.DataExpire = TimeSpan.FromMinutes(60);//测试APM缓存过期时间(默认情况下可以不用设置)
#endregion
#region 微信相关配置
/* 微信配置开始
*
* 建议按照以下顺序进行注册,尤其须将缓存放在第一位!
*/
//注册开始
#region 微信缓存(按需,必须在 register.UseSenparcWeixin() 之前)
//微信的 Redis 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错)
if (useRedis)
{
app.UseSenparcWeixinCacheRedis();
}
#endregion
//开始注册微信信息,必须!
register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting)
#region 注册公众号或小程序(按需)
//注册多个公众号或小程序(可注册多个)
.RegisterWxOpenAccount(senparcWeixinSetting, "主小程序")
//除此以外,仍然可以在程序任意地方注册公众号或小程序:
//AccessTokenContainer.Register(appId, appSecret, name);//命名空间:Senparc.Weixin.MP.Containers
#endregion
#region 注册微信支付(按需)
//注册最新微信支付版本(V3)(可注册多个)
.RegisterTenpayV3(senparcWeixinSetting, "主公众号")//记录到同一个 SenparcWeixinSettingItem 对象中
#endregion
;
/* 微信配置结束 */
#endregion
}
19
Source : FormProvider.cs
with MIT License
from alex-oswald
with MIT License
from alex-oswald
public async Task<T> GetFormAsync<T>()
where T : Form
{
// We are throttling this because there is only one gui thread
await _semapreplaced.WaitAsync();
var form = await SynchronizationContext.InvokeAsync(() => _serviceProvider.GetService<T>());
_semapreplaced.Release();
return form;
}
19
Source : WindowsFormsHostedService.cs
with MIT License
from alex-oswald
with MIT License
from alex-oswald
private void StartUiThread()
{
Application.SetHighDpiMode(_options.HighDpiMode);
if (_options.EnableVisualStyles)
{
Application.EnableVisualStyles();
}
Application.SetCompatibleTextRenderingDefault(_options.CompatibleTextRenderingDefault);
Application.ApplicationExit += OnApplicationExit;
// Don't autoinstall since we are creating our own
WindowsFormsSynchronizationContext.AutoInstall = false;
// Create the sync context on our UI thread
_formProvider.SynchronizationContext = new WindowsFormsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(_formProvider.SynchronizationContext);
var applicationContext = _serviceProvider.GetService<ApplicationContext>();
Application.Run(applicationContext);
}
19
Source : WindowsFormsHostedService.cs
with MIT License
from alex-oswald
with MIT License
from alex-oswald
private void OnApplicationStopping()
{
var applicationContext = _serviceProvider.GetService<ApplicationContext>();
var form = applicationContext.MainForm;
// If the form is closed then the handle no longer exists
// We would get an exception trying to invoke from the control when it is already closed
if (form != null && form.IsHandleCreated)
{
// If the host lifetime is stopped, gracefully close and dispose of forms in the service provider
form.Invoke(new Action(() =>
{
form.Close();
form.Dispose();
}));
}
}
19
Source : HateoasResultProvider.cs
with Apache License 2.0
from alexz76
with Apache License 2.0
from alexz76
private async Task<object> GetPolicyLinkAsync(InMemoryPolicyRepository.Policy policy, object model)
{
var uriProviderType = typeof(HateoasUriProvider<>).MakeGenericType(policy.GetType());
var uriProvider = _serviceProvider.GetService(uriProviderType);
var endpoint = (dynamic)uriProvider.GetType()
.InvokeMember(
nameof(HateoasUriProvider<InMemoryPolicyRepository.Policy>.GenerateEndpoint),
BindingFlags.InvokeMethod,
null,
uriProvider,
new[] { policy, model });
var link = new
{
Method = endpoint.Item1,
Uri = endpoint.Item2,
Relation = policy.Name,
policy.Message
};
return await Task.FromResult(link).ConfigureAwait(false);
}
19
Source : FunctionFactory.cs
with MIT License
from aliencube
with MIT License
from aliencube
public TFunction Create<TFunction, TLogger>(TLogger log) where TFunction : IFunction<TLogger>
{
if (log == null)
{
throw new ArgumentNullException(nameof(log));
}
if (!LoggerTypeValidator.ValidateLoggerType(log))
{
throw new ArgumentException("Invalid logger type");
}
var function = this._container
.GetService<TFunction>()
.AddLogger(log);
return function;
}
19
Source : IocContainer.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public object Resolve(Type type)
{
return _serviceProvider.GetService(type);
}
19
Source : ScriptComponent.cs
with MIT License
from Aminator
with MIT License
from Aminator
internal void Initialize(IServiceProvider services)
{
Services = services;
GraphicsDevice = Services.GetService<GraphicsDevice>();
Content = Services.GetRequiredService<IContentManager>();
Game = Services.GetRequiredService<IGame>();
Input = Services.GetRequiredService<InputManager>();
SceneSystem = Services.GetRequiredService<SceneSystem>();
Script = Services.GetRequiredService<ScriptSystem>();
}
19
Source : ShoppingCart.cs
with MIT License
from Amine-Smahi
with MIT License
from Amine-Smahi
public static ShoppingCart GetCart(IServiceProvider services)
{
ISession session = services.GetRequiredService<IHttpContextAccessor>()?
.HttpContext.Session;
var context = services.GetService<AppDbContext>();
string cartId = session.GetString("CartId") ?? Guid.NewGuid().ToString();
session.SetString("CartId", cartId);
return new ShoppingCart(context) { ShoppingCartId = cartId };
}
19
Source : SvnItemData.ChangeList.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
List<SvnChangeList> names = new List<SvnChangeList>();
if (context != null)
{
IAnkhPackage package = context.GetService(typeof(IAnkhPackage)) as IAnkhPackage;
if (package != null)
{
IPendingChangesManager pcm = package.GetService<IPendingChangesManager>();
foreach (string cl in pcm.GetSuggestedChangeLists())
{
names.Add(cl);
}
}
}
names.Add("ignore-on-commit");
StandardValuesCollection svc = new StandardValuesCollection(names);
return svc;
}
19
Source : AnkhModule.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[DebuggerStepThrough]
public object GetService(Type serviceType)
{
return _container.GetService(serviceType);
}
19
Source : IAnkhServiceProvider.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[DebuggerStepThrough]
public object GetService(Type serviceType)
{
object value = _parentProvider.GetService(serviceType);
if (value == null && serviceType == typeof(IAnkhServiceProvider))
return this;
return value;
}
19
Source : AnkhRuntime.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
void InitializeServices()
{
if (_servicesLoaded)
return;
if (GetService<AnkhRuntime>() == null)
{
_container.AddService(typeof(AnkhRuntime), this, true);
if (_container.GetService(typeof(IAnkhServiceProvider)) == null)
_container.AddService(typeof(IAnkhServiceProvider), this);
}
if (GetService<AnkhServiceEvents>() == null)
{
AnkhServiceEvents se = new AnkhServiceEvents(Context);
_container.AddService(typeof(AnkhServiceEvents), se);
_container.AddService(typeof(IAnkhServiceEvents), se);
}
if(GetService<SynchronizationContext>() == null)
_container.AddService(typeof(SynchronizationContext), new System.Windows.Forms.WindowsFormsSynchronizationContext());
#if DEBUG
PreloadServicesViaEnsure = true;
#endif
// If the parent container is not hooked up yet, we have to reinitialize later!
_servicesLoaded = (GetService<AnkhRuntime>() != null);
}
19
Source : AnkhRuntime.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public static AnkhRuntime Get(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
return serviceProvider.GetService(typeof(AnkhRuntime)) as AnkhRuntime;
}
19
Source : AnkhRuntime.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public void LoadServices(IServiceContainer container, System.Reflection.replacedembly replacedembly, IAnkhServiceProvider context)
{
if (replacedembly == null)
throw new ArgumentNullException("replacedembly");
else if (context == null)
throw new ArgumentNullException("context");
IAnkhStaticServiceRegistry staticContainer = container as IAnkhStaticServiceRegistry;
object[] constructorArgs = null;
foreach (Type type in replacedembly.GetTypes())
{
if (!type.IsClreplaced || type.IsAbstract || type.IsNested || !Attribute.IsDefined(type, typeof(GlobalServiceAttribute), false))
continue;
if (!typeof(IAnkhServiceImplementation).IsreplacedignableFrom(type))
{
#if DEBUG
Debug.WriteLine(string.Format("Ignoring AnkhGlobalServiceAttribute on {0} as it does not implement IAnkhServiceImplementation", type.replacedemblyQualifiedName));
#endif
continue;
}
IAnkhServiceImplementation instance = null;
foreach (GlobalServiceAttribute attr in type.GetCustomAttributes(typeof(GlobalServiceAttribute), false))
{
Type serviceType = attr.ServiceType;
#if DEBUG
if (!serviceType.IsreplacedignableFrom(type))
throw new InvalidOperationException(string.Format("{0} does not implement global service {1} but has an attribute that says it does", type.replacedemblyQualifiedName, serviceType.FullName));
#endif
if (!attr.Applies())
continue;
if (attr.AllowPreRegistered && null != (container.GetService(serviceType)))
continue;
if (instance == null)
{
try
{
ConstructorInfo ci = type.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.ExactBinding,
null, _serviceConstructorParams, null);
if (ci == null)
{
string msg = string.Format("Servicetype {0} has no valid contructor", type.replacedemblyQualifiedName);
Trace.WriteLine(msg);
throw new InvalidOperationException(msg);
}
if (constructorArgs == null)
constructorArgs = new object[] { context };
instance = (IAnkhServiceImplementation)ci.Invoke(constructorArgs);
}
catch (Exception e)
{
AnkhMessageBox mb = new AnkhMessageBox(Context);
mb.Show(e.ToString());
continue;
}
}
#if DEBUG
if (attr.PublicService && !Marshal.IsTypeVisibleFromCom(serviceType))
Trace.WriteLine(string.Format("ServiceType {0} is not visible from com, but promoted", serviceType.replacedemblyQualifiedName));
#endif
if (staticContainer != null)
staticContainer.AddStaticService(serviceType, instance, attr.PublicService);
else
container.AddService(serviceType, instance, attr.PublicService);
}
if (instance != null)
{
_services.Add(instance);
instance.OnPreInitialize();
}
}
}
19
Source : AnkhSvnPackage.ToolWindows.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public object GetService(Type serviceType)
{
if (serviceType == typeof(AmbientProperties))
{
if (Package != null)
return Package.AmbientProperties;
else
return null;
}
System.IServiceProvider paneSp = _pane;
object ob = paneSp.GetService(serviceType);
if (ob != null)
return ob;
else if (Package != null)
return Package.GetService(serviceType);
else
return null;
}
19
Source : RepositoryExplorerControl.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
protected override void OnLoad(EventArgs e)
{
IServiceContainer container = Context.GetService<IServiceContainer>();
if (container != null)
{
if (null == container.GetService(typeof(RepositoryExplorerControl)))
container.AddService(typeof(RepositoryExplorerControl), this);
}
base.OnLoad(e);
treeView.Context = Context;
fileView.Context = Context;
treeView.SelectionPublishServiceProvider = Context;
fileView.SelectionPublishServiceProvider = Context;
fileView.ColumnWidthChanged += new ColumnWidthChangedEventHandler(fileView_ColumnWidthChanged);
IDictionary<string, int> widths = ConfigurationService.GetColumnWidths(GetType());
fileView.SetColumnWidths(widths);
}
19
Source : LogToolWindowControl.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
protected override void OnLoad(EventArgs e)
{
IServiceContainer container = Context.GetService<IServiceContainer>();
if (container != null)
{
if (null == container.GetService(typeof(LogToolWindowControl)))
container.AddService(typeof(LogToolWindowControl), this);
}
base.OnLoad(e);
}
See More Examples