Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从Asp.net核心依赖注入中注册的子类解析父类实例_C#_Asp.net Core_Dependency Injection_Asp.net Identity_Dbcontext - Fatal编程技术网

C# 如何从Asp.net核心依赖注入中注册的子类解析父类实例

C# 如何从Asp.net核心依赖注入中注册的子类解析父类实例,c#,asp.net-core,dependency-injection,asp.net-identity,dbcontext,C#,Asp.net Core,Dependency Injection,Asp.net Identity,Dbcontext,假设我有一门课 abstract class CustomContext: IdentityDbContext<AppUser, Role>{} class TContext: CustomContext{} 但在程序中的某个地方,我想解析CustomContext的实例将抽象注册到解析实现的委托工厂 services.AddScoped<CusomContext>(sp => sp.GetRequiredService<TContext>());

假设我有一门课

abstract class CustomContext: IdentityDbContext<AppUser, Role>{}

class TContext: CustomContext{}

但在程序中的某个地方,我想解析CustomContext的实例

将抽象注册到解析实现的委托工厂

services.AddScoped<CusomContext>(sp => sp.GetRequiredService<TContext>());
services.addScope(sp=>sp.GetRequiredService());

这样,当请求抽象时,试图解析抽象的容器就会知道它。

向解析实现的委托工厂注册抽象

services.AddScoped<CusomContext>(sp => sp.GetRequiredService<TContext>());
services.addScope(sp=>sp.GetRequiredService());

这样,当请求抽象时,试图解析它的容器就会知道它。

CustomContext是一个抽象类,如果该类存在,您将无法创建或解析实例。您仍然可以执行
CustomContext c=ServicesCollector.Container.GetService(typeof(TContext))
谢谢您的回复。但在可访问CustomContext的层中,TContext不可用。与CustomContext类似,CustomContext位于父程序集中,而TContext在子级可用。我有权访问ServicesCollection,但我不确定如何解析上下文,然后按照您所说的将其分配给CustomContext。CustomContext是一个抽象类,如果该类存在,您将无法创建或解析实例。您仍然可以执行
CustomContext c=ServicesCollector.Container.GetService(typeof(TContext))
谢谢您的回复。但在可访问CustomContext的层中,TContext不可用。与CustomContext类似,CustomContext位于父程序集中,而TContext在子级可用。我有权访问ServicesCollection,但我不确定如何解析上下文,然后按照您所说的将其分配给CustomContext。
services.AddScoped<CusomContext>(sp => sp.GetRequiredService<TContext>());