问题描述
我已经为我的ASP.NET核心Web应用程序实现了 EntityFrameworkFileProvider
,我希望 ViewDbContext
实例由ASP.NET核心DI框架在构造函数中注入:
I have implemented the EntityFrameworkFileProvider
for my ASP.NET core web application, I want the ViewDbContext
instance to be injected by ASP.NET core DI framework in the constructor:
( ViewDbContext
是 dbContext
)
public class EntityFrameworkFileProvider : IFileProvider
{
private ViewDbContext _context;
public EntityFrameworkFileProvider(ViewDbContext context)
{
/* should be injected by asp.net core DI */
_context = context;
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
.....
}
public IFileInfo GetFileInfo(string subpath)
{
var result = new DatabaseFileInfo(_context, subpath);
return result.Exists ? result as IFileInfo : new NotFoundFileInfo(subpath);
}
public IChangeToken Watch(string filter)
{
return new DatabaseChangeToken(_context, filter);
}
}
现在,我在startup.cs中将 EntityFrameworkFileProvider
添加到 RazorViewEngineOption
如何使 ViewDbContext
实例可以由DI框架在startup.cs的 ConfigureServices
方法中自动注入?我应该如何正确调用 EntityFrameworkFileProvider
构造函数?
Now I add the EntityFrameworkFileProvider
to RazorViewEngineOption
in startup.csHow to make the ViewDbContext
instance to be automatically injected by DI framework in the ConfigureServices
method of startup.cs? how should i call the EntityFrameworkFileProvider
constructor correctly?
在Startup.cs
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
/* Add EntityFrameworkFileProvider to Razor engine */
services.Configure<RazorViewEngineOptions>(opts =>
{
opts.FileProviders.Add(new EntityFrameworkFileProvider(null?));
});
services.AddMvc();
}
推荐答案
我认为我已经找到了解决方案!有什么主意吗?
i think i have found the solution! any idea?
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ViewDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...
/* Add EntityFrameworkFileProvider to Razor engine */
var context = services.BuildServiceProvider()
.GetService<ViewDbContext>();
services.Configure<RazorViewEngineOptions>(opts =>
{
opts.FileProviders.Add(new EntityFrameworkFileProvider(context));
});
services.AddMvc();
}
这篇关于如何在startup.cs(ASP.net core 1.1)的ConfigureServices方法中正确注入DbContext实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!