How to inject DbContext instance in the ConfigureServices method of startup.cs correctly (ASP.net core 1.1)?

我是研究僧i 提交于 2021-01-27 07:03:04

问题


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 is a 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);
    }
}

Now I add the EntityFrameworkFileProvider to RazorViewEngineOption in startup.cs How 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?

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

回答1:


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



回答2:


A better approach would be to inject the context in Configure method and use it it there

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ViewDbContext context)
{
     services.AddDbContext<ViewDbContext>(options => 
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    ...
     /* Add  EntityFrameworkFileProvider to Razor engine */       
     /* Use db context here*/

     services.Configure<RazorViewEngineOptions>(opts =>
     {
         opts.FileProviders.Add(new EntityFrameworkFileProvider(context));
     });

     services.AddMvc();
}



回答3:


you should Use this code in startup.cs in ConfigureServices method:

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

and for define DefaultConnection go to Project's Json file and add this text:

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

this trick was useful for me.



来源:https://stackoverflow.com/questions/41411384/how-to-inject-dbcontext-instance-in-the-configureservices-method-of-startup-cs-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!