【问题标题】:Auto Inject All Services in .net core AutoFac在 .net core AutoFac 中自动注入所有服务
【发布时间】: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


    【解决方案1】:

    您可以为此使用 AssemblyScanning 内置的 AutoFacs。

    以下示例将注册所有继承自AppService 的类作为它们的具体类型。

    builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
           .Where(t => t.BaseType == typeof(AppService))
           .AsSelf();
    

    这将允许您从容器中解析 CountryServiceTestService

    【讨论】:

    • Itried 你的解决方案,我得到了这个期望(不同项目中的 appService 是改变事情吗?)处理请求时发生未处理的异常。 InvalidOperationException:无法解析类型 ' 的服务
    • @AYKHO 如果它在不同的项目中,请尝试 (builder.RegisterAssemblyTypes(typeof(AppService).Assembly))
    • 同样的异常仍然无法注入
    • 您能否更新您的问题以显示您如何尝试解决依赖关系?
    • 我发现我的问题是在 .net 核心中我更改为使用 Autofac 模块,感谢 Fermin
    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 2018-10-12
    • 1970-01-01
    • 2021-09-05
    • 2019-05-27
    • 2020-11-24
    • 1970-01-01
    • 2020-08-21
    相关资源
    最近更新 更多