【发布时间】:2017-05-23 14:32:18
【问题描述】:
我一直在努力寻找最好/首选的方法是让我的RoleService 获得ConfigurationDbContext (IdentityServer4)。
我真的很想解耦,以便我的 RoleService 可以测试。
我发现访问ConfigurationDbContext 的唯一方法是在Startup.cs 中创建public static IServiceProvider:
public class Startup
{
private readonly IHostingEnvironment _environment;
// THIS IS THE PROPERTY I USED
public static IServiceProvider ServiceProvider { get; private set; }
public ConfigurationDbContext GetConfigurationDbContext()
{
return null;
}
public Startup(ILoggerFactory loggerFactory, IHostingEnvironment environment)
{
loggerFactory.AddConsole(LogLevel.Debug);
_environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{
var connectionString = DbSettings.IdentityServerConnectionString;
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
// configure identity server with in-memory stores, keys, clients and scopes
var identityServerConfig = services.AddIdentityServer()
.AddConfigurationStore(builder =>
builder.UseSqlServer(connectionString, options =>
options.MigrationsAssembly(migrationsAssembly)))
.AddOperationalStore(builder =>
builder.UseSqlServer(connectionString, options =>
options.MigrationsAssembly(migrationsAssembly)))
.AddSigningCredential(new X509Certificate2(Path.Combine(_environment.ContentRootPath, "certs", "IdentityServer4Auth.pfx"), "test"));
identityServerConfig.Services.AddTransient<IResourceOwnerPasswordValidator, ActiveDirectoryPasswordValidator>();
identityServerConfig.Services.AddTransient<IProfileService, CustomProfileService>();
services.AddDbContext<ConfigurationDbContext>(options => options.UseSqlServer(connectionString));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
ServiceProvider = app.ApplicationServices;
// other code emitted
}
}
然后在 RoleService.cs:
public class RoleService : IRoleService
{
public async Task<ApiResource[]> GetApiResourcesByIds(int[] ids)
{
ApiResource[] result;
using (var serviceScope = Startup.ServiceProvider.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
result =
context.ApiResources.Where(x => ids.Contains(x.Id))
.Include(x => x.Scopes)
.Include(x => x.UserClaims)
.ToArray();
return result;
}
}
}
这是在RoleService.cs 中获得依赖的最佳方式吗?
有没有办法抽象serviceScope(因为它在using语句中,可能是IDisposable,我真的不知道是否有办法抽象获得context?
还有其他建议或最佳做法吗?
【问题讨论】:
标签: c# asp.net-core .net-core entity-framework-core identityserver4