1

我正在尝试从数据库加载视图,并且正如文章中所建议的那样,可能需要添加一些缓存以防止每次都访问数据库。

ConfigureServices

services.AddHttpContextAccessor();
services.AddMemoryCache();

services.AddRazorPages()
    .AddRazorRuntimeCompilation(opt =>
    {
        opt.FileProviders.Add(new DatabaseFileProvider(Configuration["AppSettings:SQLConnectionString"]));
    });

DatabaseFileProvider构造函数:

private string _connection;

public DatabaseFileProvider(string connection)
{
    _connection = connection;
}

我如何依赖注入类的实例IMemoryCacheDatabaseFileProvider,就像一个单例一样:

ConfigureServices

services.AddSingleton<AppUtils>();

AppUtils构造函数:

private static IMemoryCache _cache;

public AppUtils(IMemoryCache cache)
{
    _cache = cache;
}
4

1 回答 1

4

使用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();
于 2021-06-11T23:46:22.637 回答