【问题标题】:Net Core 3.0 dependency injection interface that the dbcontext derived fromdbcontext 派生自的 Net Core 3.0 依赖注入接口
【发布时间】:2020-09-12 16:43:35
【问题描述】:

有没有办法依赖注入接口 DbContext 派生自 Startup 类?

下面是DbContent

public partial class SRSDbContext : IdentityDbContext<SRSIdentityUser>, ISRSDbContext
{
    public SRSDbContext() 
    {

//...

Startup 类中我尝试使用代码

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ISRSDbContext>(opts =>
        opts.UseSqlServer(Configuration.GetConnectionString("sqlConnection")));

但是ISRSDbContext接口在上面这行代码中没有被识别出来。

我喜欢使用AppsSetting.json 文件中定义的连接字符串注册ISRSDbContext 以进行依赖注入

【问题讨论】:

    标签: c# dependency-injection entity-framework-core asp.net-core-webapi asp.net-core-3.1


    【解决方案1】:

    使用采用接口及其派生实现的AddDbContext 重载

    //...
    
    services.AddDbContext<ISRSDbContext, SRSDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("sqlConnection")));
    
    //...
    

    如果接口是在单独的库中注册的,还要确保它被调用代码的库引用。

    【讨论】:

    • 嘿,谢谢。我尝试将 Autofac 与 Net Core 一起使用,但在将 Autofac 与 .Net Core 一起使用时,我遇到了很多编译错误和令人头疼的问题,我刚刚放弃了。当我将 Autofac 与 NetFramework 一起使用时,它工作得很好,但它给我带来了很多 .Net Core 的问题。我在 Autofac 博客上发布了有关这些问题的问题,但要么没有答案,要么答案告诉我查看提供少量信息的 autofac 文档
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2019-04-13
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多