【发布时间】:2020-04-24 21:05:37
【问题描述】:
我有服务基类和不同的子类从它继承我如何注入所有服务实现这个类
public abstract class AppService
{
public string ServiceName {get;set;}
}
我还有其他课程
public class CountryService:AppService
{
public list<Countries> getCountryByName(string name){
return ......
}
}
public class TestService:AppService
{
public void Test(){
return ......
}
}
如何自动注入从 AppService 继承的任何类,而无需手动在 StartUp 中添加此类
更新**********************
我在startUp中使用如下注册服务
services.Configure<ServiceConfig>(config =>
{
config.Services = new List<ServiceDescriptor>(services);
config.Path = "/listservices";
});
ContainerSetup.InitializeWeb(Assembly.GetExecutingAssembly(), services);
在 Services 项目中,这里是容器设置:
public static IServiceProvider InitializeWeb(Assembly webAssembly, IServiceCollection services) =>
new AutofacServiceProvider(BaseAutofacInitialization(setupAction =>
{
setupAction.Populate(services);
setupAction.RegisterAssemblyTypes(webAssembly).AsSelf();
}));
public static IContainer BaseAutofacInitialization(Action<ContainerBuilder> setupAction = null)
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.BaseType == typeof(AppService))
.AsSelf();
setupAction?.Invoke(builder);
return builder.Build();
}
仍然出现错误 处理请求时发生未处理的异常。 InvalidOperationException:无法解析类型的服务
【问题讨论】:
标签: asp.net-core dependency-injection autofac .net-core-3.0