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

时间:2016-12-31 20:08:13

标签: c# dependency-injection asp.net-core entity-framework-core

我已经为我的ASP.NET核心Web应用程序实现了EntityFrameworkFileProvider,我希望构造函数中的ASP.NET核心DI框架注入ViewDbContext实例:

ViewDbContextdbContext

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实例在startup.cs的ConfigureServices方法中由DI框架自动注入?我该如何正确调用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();
}

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:1)

一种更好的方法是将上下文注入Configure方法中并在其中使用它

CELERY_BROKER_URL= "{AMQP URL}"

答案 2 :(得分:0)

您应该在configure.services方法的startup.cs中使用以下代码:

 public void ConfigureServices(IServiceCollection services)
    {
         services.AddDbContext<ViewDbContext>(options => 
        
   options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
         var context = services.BuildServiceProvider()
                           .GetService<ViewDbContext>();
    
         services.Configure<RazorViewEngineOptions>(opts =>
         {
             opts.FileProviders.Add(new EntityFrameworkFileProvider(context));
         });
    
         services.AddMvc();
    }

并为定义DefaultConnection转到Project的Json文件并添加以下文本:

"ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog='your db name';
Integrated Security=true"
  }

这个技巧对我很有用。