使用DI服务MvcRazorRuntimeCompilationOptions
直接配置
假设一个目标提供者像
public class DatabaseFileProvider : IFileProvider {
private string connection;
private IMemoryCache cache;
public DatabaseFileProvider(string connection, IMemoryCache cache) {
this.connection = connection;
this.cache = cache;
}
//...
}
借助 DI 服务创建提供程序将允许使用延迟配置委托解析和显式注入任何已注册的依赖项。
参考使用 DI 服务配置选项
services.AddHttpContextAccessor();
services.AddMemoryCache();
services
.AddOptions<MvcRazorRuntimeCompilationOptions>()
.Configure<IServiceProvider>((options, sp) => { //<-- Configuration here
var cs = Configuration["AppSettings:SQLConnectionString"]);
var provider = ActivatorUtilities.CreateInstance<DatabaseFileProvider>(sp, cs);
options.FileProviders.Add(provider);
});
services.AddRazorPages()
.AddRazorRuntimeCompilation(); //remove configuration delegate here
Configure
允许使用最多五个服务来配置选项,但是如果IServiceProvider
注入了 a,则可以在需要时使用提供程序来解决更多依赖关系。
如果该服务定位器方法不是首选,则可以重新安排设置以遵循更纯粹的 DI 设计。
services.AddHttpContextAccessor();
services.AddMemoryCache();
service.AddTransient<IFileProvider, DatabaseFileProvider>(sp => {
var cs = Configuration["AppSettings:SQLConnectionString"]);
var provider = ActivatorUtilities.CreateInstance<DatabaseFileProvider>(sp, cs);
return provider;
});
//... register other providers if any
services
.AddOptions<MvcRazorRuntimeCompilationOptions>()
.Configure<IEnumerable<IFileProvider>>((options, providers) => {
//add all registered providers
foreach(IFileProvider provider in providers) {
options.FileProviders.Add(provider);
}
});
services.AddRazorPages()
.AddRazorRuntimeCompilation();