Here are the examples of the csharp api System.IServiceProvider.GetServices() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
14 Examples
19
Source : SQLiteCachingTest.cs
with MIT License
from dotnetcore
with MIT License
from dotnetcore
protected override IEasyCachingProvider CreateCachingProvider(Action<BaseProviderOptions> additionalSetup)
{
IServiceCollection services = new ServiceCollection();
services.AddEasyCaching(x =>
x.UseSQLite(options =>
{
options.DBConfig = new SQLiteDBOptions
{
FileName = "s1.db",
CacheMode = Microsoft.Data.Sqlite.SqliteCacheMode.Default,
OpenMode = Microsoft.Data.Sqlite.SqliteOpenMode.Memory,
};
additionalSetup(options);
})
);
IServiceProvider serviceProvider = services.BuildServiceProvider();
var dbProvider = serviceProvider.GetServices<ISQLiteDatabaseProvider>().First();
var conn = dbProvider.GetConnection();
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
conn.Execute(ConstSQL.CREATESQL);
return serviceProvider.GetService<IEasyCachingProvider>();
}
19
Source : ServiceLocator.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public IEnumerable<T> GetServices<T>()
{
Check.NotNull(_services, nameof(_services));
Check.NotNull(_provider, nameof(_provider));
IScopedServiceResolver scopedResolver = _provider.GetService<IScopedServiceResolver>();
if (scopedResolver != null && scopedResolver.ResolveEnabled)
{
return scopedResolver.GetServices<T>();
}
return _provider.GetServices<T>();
}
19
Source : TransactionalAttribute.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public override async Task Invoke(AspectContext context, AspectDelegate next)
{
IServiceProvider provider = context.ServiceProvider;
IUnitOfWork unitOfWork = provider.GetUnitOfWork(true);
try
{
await next(context);
if (!RequiredCheckReturnValue)
{
#if NET5_0
await unitOfWork.CommitAsync();
#else
unitOfWork.Commit();
#endif
return;
}
Type returnType = context.ProxyMethod.ReturnType;
ITransactionDecision decision = provider.GetServices<ITransactionDecision>()
.FirstOrDefault(m => m.IsFit(returnType));
if (decision == null)
{
throw new OsharpException($"无法找到与结果类型 {returnType} 匹配的 {typeof(ITransactionDecision)} 事务裁决器,请继承接口实现一个");
}
if (decision.CanCommit(context.ReturnValue))
{
#if NET5_0
await unitOfWork.CommitAsync();
#else
unitOfWork.Commit();
#endif
}
}
catch (Exception)
{
#if NET5_0
await unitOfWork.CommitAsync();
#else
unitOfWork.Commit();
#endif
throw;
}
}
19
Source : ServiceExtensions.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public static OsharpPack[] GetAllPacks(this IServiceProvider provider)
{
OsharpPack[] packs = provider.GetServices<OsharpPack>().OrderBy(m => m.Level).ThenBy(m => m.Order).ThenBy(m => m.GetType().FullName).ToArray();
return packs;
}
19
Source : ServiceExtensions.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public static IServiceProvider UseOsharp(this IServiceProvider provider)
{
ILogger logger = provider.GetLogger(typeof(ServiceExtensions));
logger.LogInformation("OSharp框架初始化开始");
Stopwatch watch = Stopwatch.StartNew();
OsharpPack[] packs = provider.GetServices<OsharpPack>().ToArray();
foreach (OsharpPack pack in packs)
{
pack.UsePack(provider);
logger.LogInformation($"模块{pack.GetType()}加载成功");
}
watch.Stop();
logger.LogInformation($"OSharp框架初始化完毕,耗时:{watch.Elapsed}");
return provider;
}
19
Source : AutoMapperPack.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public override void UsePack(IServiceProvider provider)
{
ILogger logger = provider.GetLogger<AutoMapperPack>();
MapperConfigurationExpression cfg = provider.GetService<MapperConfigurationExpression>();
//获取已注册到IoC的所有Profile
IMapTuple[] tuples = provider.GetServices<IMapTuple>().OrderBy(m => m.Order).ToArray();
foreach (IMapTuple mapTuple in tuples)
{
mapTuple.CreateMap();
cfg.AddProfile(mapTuple as Profile);
logger.LogInformation($"初始化对象映射配对:{mapTuple.GetType()}");
}
var configuration = new MapperConfiguration(cfg);
IMapper mapper = new AutoMapperMapper(configuration);
MapperExtensions.SetMapper(mapper);
logger.LogInformation($"初始化对象映射对象到 MapperExtensions:{mapper.GetType()},共包含 {configuration.GetMappers().Count()} 个映射配对");
IsEnabled = true;
}
19
Source : DbContextBase.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//通过实体配置信息将实体注册到当前上下文
Type contextType = GetType();
IEnreplacedyRegister[] registers = _enreplacedyManager.GetEnreplacedyRegisters(contextType);
foreach (IEnreplacedyRegister register in registers)
{
register.RegisterTo(modelBuilder);
Logger.LogDebug($"将实体类 {register.EnreplacedyType} 注册到上下文 {contextType} 中");
}
Logger.LogInformation($"上下文 {contextType} 注册了{registers.Length}个实体类");
// 应用批量实体配置
List<IMutableEnreplacedyType> mutableEnreplacedyTypes = modelBuilder.Model.GetEnreplacedyTypes().ToList();
IEnreplacedyBatchConfiguration[] enreplacedyBatchConfigurations =
_serviceProvider.GetServices<IEnreplacedyBatchConfiguration>().ToArray();
if (enreplacedyBatchConfigurations.Length > 0)
{
foreach (IMutableEnreplacedyType mutableEnreplacedyType in mutableEnreplacedyTypes)
{
foreach (IEnreplacedyBatchConfiguration enreplacedyBatchConfiguration in enreplacedyBatchConfigurations)
{
enreplacedyBatchConfiguration.Configure(modelBuilder, mutableEnreplacedyType);
}
}
}
}
19
Source : Repository.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
private void SetEmptyGuidKey(TEnreplacedy enreplacedy)
{
Type keyType = typeof(TKey);
//自增int
if (keyType == typeof(int))
{
IKeyGenerator<int> generator = _serviceProvider.GetService<IKeyGenerator<int>>();
enreplacedy.Id = generator.Create().CastTo<TKey>();
return;
}
//雪花long
if (keyType == typeof(long) && enreplacedy.Id.Equals(default(long)))
{
IKeyGenerator<long> generator = _serviceProvider.GetService<IKeyGenerator<long>>();
enreplacedy.Id = generator.Create().CastTo<TKey>();
}
//顺序guid
if (keyType == typeof(Guid) && enreplacedy.Id.Equals(Guid.Empty))
{
DatabaseType databaseType = _dbContext.GetDatabaseType();
ISequentialGuidGenerator generator =
_serviceProvider.GetServices<ISequentialGuidGenerator>().FirstOrDefault(m => m.DatabaseType == databaseType);
enreplacedy.Id = generator == null ? SequentialGuid.Create(databaseType).CastTo<TKey>() : generator.Create().CastTo<TKey>();
}
}
19
Source : PluginManager.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
private IEnumerable<TPlugin> ResolvePlugins<TPlugin>() where TPlugin : IPlugin
{
var plugins = _serviceProvider.GetServices<TPlugin>();
foreach (var plugin in plugins)
{
if (!plugin.Initialized)
{
var pluginType = plugin.GetType();
var names = pluginType.replacedemblyQualifiedName.Split(',');
var typeName = names[0].Trim();
var replacedName = names[1].Trim();
var pluginConfig = _smartCodeOptions
.Plugins
.FirstOrDefault(m => m.ImplreplacedemblyName == replacedName && m.ImplTypeName == typeName);
plugin.Initialize(pluginConfig.Parameters);
}
}
return plugins;
}
19
Source : SmartSqlExtensions.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public static SmartSqlBuilder GetSmartSql(this IServiceProvider sp, string alias = SmartSqlBuilder.DEFAULT_ALIAS)
{
return sp.GetServices<SmartSqlBuilder>().FirstOrDefault(m => m.Alias == alias);
}
19
Source : SmartSqlDIExtensions.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public static IServiceProvider UseSmartSqlSync(this IServiceProvider serviceProvider)
{
var syncService = serviceProvider.GetRequiredService<ISyncService>();
foreach (var smartSqlBuilder in serviceProvider.GetServices<SmartSqlBuilder>())
{
smartSqlBuilder.SmartSqlConfig.InvokeSucceedListener.InvokeSucceeded += (sender, args) =>
{
syncService.Sync(args.ExecutionContext);
};
}
return serviceProvider;
}
19
Source : SmartSqlDIExtensions.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public static IServiceProvider UseSmartSqlSubscriber(this IServiceProvider serviceProvider,
Action<SyncRequest> onReceived)
{
if (onReceived == null) throw new ArgumentNullException(nameof(onReceived));
var subscribers = serviceProvider.GetServices<ISubscriber>();
foreach (var subscriber in subscribers)
{
subscriber.Received += (sender, request) => { onReceived(request); };
subscriber.Start();
}
return serviceProvider;
}
19
Source : MigrationPackBase.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public override void UsePack(IServiceProvider provider)
{
OsharpOptions options = provider.GetOSharpOptions();
OsharpDbContextOptions contextOptions = options.GetDbContextOptions(typeof(TDbContext));
if (contextOptions?.DatabaseType != DatabaseType)
{
return;
}
ILogger logger = provider.GetLogger(GetType());
using (IServiceScope scope = provider.CreateScope())
{
TDbContext context = CreateDbContext(scope.ServiceProvider);
if (context != null && contextOptions.AutoMigrationEnabled)
{
context.CheckAndMigration(logger);
DbContextModelCache modelCache = scope.ServiceProvider.GetService<DbContextModelCache>();
modelCache?.Set(context.GetType(), context.Model);
}
}
//初始化种子数据,只初始化当前上下文的种子数据
IEnreplacedyManager enreplacedyManager = provider.GetService<IEnreplacedyManager>();
Type[] enreplacedyTypes = enreplacedyManager.GetEnreplacedyRegisters(typeof(TDbContext)).Select(m => m.EnreplacedyType).Distinct().ToArray();
IEnumerable<ISeedDataInitializer> seedDataInitializers = provider.GetServices<ISeedDataInitializer>()
.Where(m => enreplacedyTypes.Contains(m.EnreplacedyType)).OrderBy(m => m.Order);
foreach (ISeedDataInitializer initializer in seedDataInitializers)
{
initializer.Initialize();
}
IsEnabled = true;
}
19
Source : ServiceExtensions.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public static DbContextOptionsBuilder BuildDbContextOptionsBuilder<TDbContext>(this IServiceProvider provider, DbContextOptionsBuilder builder)
where TDbContext : DbContext
{
Type dbContextType = typeof(TDbContext);
OsharpOptions osharpOptions = provider.GetOSharpOptions();
OsharpDbContextOptions osharpDbContextOptions = osharpOptions?.GetDbContextOptions(dbContextType);
if (osharpDbContextOptions == null)
{
throw new OsharpException($"无法找到数据上下文 {dbContextType.DisplayName()} 的配置信息");
}
ILogger logger = provider.GetLogger(typeof(ServiceExtensions));
//启用延迟加载
if (osharpDbContextOptions.LazyLoadingProxiesEnabled)
{
builder = builder.UseLazyLoadingProxies();
logger.LogDebug($"数据上下文类型 {dbContextType} 应用延迟加载代理");
}
DatabaseType databaseType = osharpDbContextOptions.DatabaseType;
//处理数据库驱动差异处理
IDbContextOptionsBuilderDriveHandler driveHandler = provider.GetServices<IDbContextOptionsBuilderDriveHandler>()
.LastOrDefault(m => m.Type == databaseType);
if (driveHandler == null)
{
throw new OsharpException($"无法解析类型为 {databaseType} 的 {typeof(IDbContextOptionsBuilderDriveHandler).DisplayName()} 实例");
}
//选择主/从数据库连接串
IConnectionStringProvider connectionStringProvider = provider.GetRequiredService<IConnectionStringProvider>();
string connectionString = connectionStringProvider.GetConnectionString(typeof(TDbContext));
ScopedDictionary scopedDictionary = provider.GetService<ScopedDictionary>();
string key = $"DbConnection_{connectionString}";
DbConnection existingDbConnection = scopedDictionary.GetValue<DbConnection>(key);
builder = driveHandler.Handle(builder, connectionString, existingDbConnection);
//使用模型缓存
DbContextModelCache modelCache = provider.GetService<DbContextModelCache>();
IModel model = modelCache?.Get(dbContextType);
if (model != null)
{
builder = builder.UseModel(model);
}
return builder;
}