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>());