Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 282
dinner689 Avatar asked Dec 31 '16 20:12

dinner689


People also ask

What ConfigureServices () method does in startup CS?

The startup class contains two methods: ConfigureServices(): Registers the services that your application will need. Configure(): Configures the middleware pipeline that controls how the application processes the HTTP requests and sends the response.

What is DbContext in ASP.NET Core?

A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns. Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance.

Which method is used for adding DbContext class as service?

The AddDbContext extension method registers DbContext types with a scoped lifetime by default.


2 Answers

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();
}
like image 52
dinner689 Avatar answered Oct 05 '22 23:10

dinner689


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();
}
like image 27
Rao khurram adeel Avatar answered Oct 05 '22 23:10

Rao khurram adeel