Entity framework 将依赖项解析为.Net core中的父项
当容器中只注册了一个子类时,是否可以解析父对象 这是我的案子。我注册了从Entity framework 将依赖项解析为.Net core中的父项,entity-framework,dependency-injection,asp.net-core-mvc,.net-core,dbcontext,Entity Framework,Dependency Injection,Asp.net Core Mvc,.net Core,Dbcontext,当容器中只注册了一个子类时,是否可以解析父对象 这是我的案子。我注册了从DbContext派生的MyDbContext services.AddDbContext<MyDbContext>(options =>options.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly))); 目前,我得到上述代码为
DbContext
派生的MyDbContext
services.AddDbContext<MyDbContext>(options =>options.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly)));
目前,我得到上述代码为空。有没有可能通过某种方式解决这个问题。我需要做到这一点,因为上面的代码是在中间件(框架/基础结构代码)中。p> 您需要向DI容器注册
DbContext
,以便在解析时可以对其进行映射
services.AddScoped<DbContext, MyDbContext>();
services.addScope();
这样,无论何时请求
DbContext
,它都将解析为MyDbContext
,前提是您向DI容器注册它。ieservices.addScope()代码>
DbContext applicationContext = context.RequestServices.GetService<DbContext>();