asp.net - How do I inject a DBContext into a service in Startup?
问题描述
I have a service that I want to use in a .Net core Blazor app.
The service uses a context that I want to pass to it.
public class MyService
{
public AddDbContextContext { get; set; }
public MyService(AddDbContext mycontext)
{
Context = mycontext;
}
}
In Startup, I create the context that I want the service to use:
public void ConfigureServices(IServiceCollection services)
{
//configure the context
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("HIDDEN"));
//how do I pass the context?
services.AddSingleton<MyService>();
}
How do I pass the context to service?
解决方案
How do I pass the context to service?
You don't pass the context to the service. It is automatically done when the DI container creates your service.
Since your DBContext is named ApplicationDbContext, your service should look like this:
public class MyService
{
private ApplicationDbContext _context;
public MyService(ApplicationDbContext context)
{
_context = context;
}
}
Note: You can only use DBContext in Blazor Server App
Note: I've only answered your question here. But it's very likely you'll have issues with the DBContext, depending on what you do in your service. You should consult the documents how to use the DBContext in Blazor, particularly, why and how you should use AddDbContextFactory
推荐阅读
- docker - 无法在 docker logs -f 命令中找到初始 jenkins 密码
- react-native - 调度操作后 Redux 状态未更新
- swift - Swift 5 Tab View (macOS) 无法确认我给出的宽度
- javascript - 如何通过输入链接从另一个页面复制到我的页面
我想在我的网站上看到
<table class = "plan">
通过我的 css 和 js 代码从学校网站编辑的内容。我试过
<iframe>
了,但这不是我想要的,$ ('# target-div').
Load ('example.com');
但它是:- themes - 如何使用 gatsby-plugin-theme-ui 调整正文背景颜色
- java - 即使缓存被命中,Memcached 也会返回 null
- facebook-graph-api - 如何使用 FB Graph Api (Instagram) 正确过滤嵌套查询?
- nextflow - 如何收集 Nextflow 流程的有序输出?
- html - Css 强制 div 填充它和页脚之间的空间
- c++ - QToolButton 上的文本未绘制