【发布时间】:2018-04-28 07:05:56
【问题描述】:
我有一个 Asp.net core 2 应用程序,我在其中配置了一个带有存储库模式和工作单元的 dbContext。
一切正常,我可以在控制器中访问 UnitOfWork 并获取数据。
我正在尝试访问中间件中的上下文以及另一个项目中的类,但我真的不知道哪种方法是最好的。
数据库上下文
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
:base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
...
}
启动
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<BloggingContext>(options => options.UseMySQL(configuration.GetConnectionString("DefaultDb")));
services.AddScoped<IBloggingContext, BloggingContext>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
...
}
中间件
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>();
}
}
我在 Invoke 函数中所做的是:
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseMySQL(_configuration.GetConnectionString("DefaultDb"));
using (var dbContext = new BloggingContext(optionsBuilder.Options))
{
var blog = dbContext.Blogs.FirstOrDefault();
...
}
我很确定这不是最好的方法。此外,理想的方法是像我在控制器中访问一样直接访问 UnitOfWork,但我不知道这是否可能。
另外,我需要在不同项目的一个类中访问相同的 DbCONtext,在这种情况下我还有另一个问题:如何访问我的 web 项目的 appsettings.json 中的配置连接字符串。
谁能帮助我了解如何在新的 asp.net core 2 中做到这一点?
另外,如果有人需要更多代码,我不介意分享我所拥有的,如果它可以帮助其他人。
提前致谢。
【问题讨论】:
标签: asp.net-core-2.0 dbcontext unit-of-work