I have an Asp.net core 2 application where I've configued a dbContext with a repository pattern and unit of work.
Everything works fine, I can access the UnitOfWork within a controller and get data.
I'm trying to access the context within a Middleware and also a class in another project, but I don't really know which is the best way.
DbContext
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
:base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
...
}
Startup
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<BloggingContext>(options => options.UseMySQL(configuration.GetConnectionString("DefaultDb")));
services.AddScoped<IBloggingContext, BloggingContext>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
...
}
Middleware
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseMyMiddleware();
...
}
public class MyMiddleware
{
private readonly RequestDelegate _next;
private readonly IConfiguration _configuration;
private readonly IMemoryCache _memoryCache;
public MyMiddleware(RequestDelegate next, IConfiguration configuration, IMemoryCache memoryCache)
{
_next = next;
_configuration = configuration;
_memoryCache = memoryCache;
}
public Task Invoke(HttpContext httpContext)
{
...
HERE I NEED TO ACCESS DATABASE
...
return _next(httpContext);
}
}
public static class MyMiddlewareExtensions
{
public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}
What I'm doing inside the Invoke function is:
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseMySQL(_configuration.GetConnectionString("DefaultDb"));
using (var dbContext = new BloggingContext(optionsBuilder.Options))
{
var blog = dbContext.Blogs.FirstOrDefault();
...
}
I'm pretty sure this is not the best way. Also the ideal way would be accesing like I access in a controller, directly to the UnitOfWork without, but I don't know if this is possible.
Also, I need to access to the same DbCOntext within a class in a different project, and in that case I have another problem: how to access the Configuration connection string which is in the appsettings.json of my web project.
Could anyone help me understanding how to do this in the new asp.net core 2?
Also, if someone needs more code I don't mind sharing what I have if it helps others.
Thanks in advance.