如何正確地在startup.cs的ConfigureServices方法中註入DbContext實例(ASP.net核心1.1)?

asp.net-core c# dependency-injection entity-framework-core

我為我的ASP.NET核心Web應用程序實現了EntityFrameworkFileProvider ,我想在構造函數中由ASP.NET核心DI框架注入ViewDbContext實例:

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中如何在ViewDbContextConfigureServices方法ViewDbContext DI框架自動注入ViewDbContext實例?我應該如何正確調用EntityFrameworkFileProvider構造函數?

在Startup.cs中

public void ConfigureServices(IServiceCollection services)
{
      /* Add  EntityFrameworkFileProvider to Razor engine */
      services.Configure<RazorViewEngineOptions>(opts =>
      {
          opts.FileProviders.Add(new EntityFrameworkFileProvider(null?));
      });

      services.AddMvc();
}

一般承認的答案

我想我找到了解決方案!任何想法?

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();
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow