自动在.net core AutoFac中注入所有服务

问题描述 投票:0回答:1

我有服务基类,并且不同的子类从中继承了如何注入所有实现该类的服务

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中手动添加该类

更新*********************

我正在使用以下内容在启动中注册服务

 services.Configure<ServiceConfig>(config =>
            {
                config.Services = new List<ServiceDescriptor>(services);
                config.Path = "/listservices";
            });

            ContainerSetup.InitializeWeb(Assembly.GetExecutingAssembly(), services);

并且在Services项目中,这里是容器Setup:

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:无法解析类型为>>的服务

我有服务基类,并且不同的子类继承了它,因此我可以注入所有服务来实现该类。公共抽象类AppService {公共字符串ServiceName {get; set;}}和...

asp.net-core dependency-injection autofac .net-core-3.0
1个回答
0
投票
您可以为此使用AssemblyScanning内置的AutoFac。
© www.soinside.com 2019 - 2024. All rights reserved.