使用未知类型的Autofac C#中的动态TypeRegistration

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

我正在尝试创建一个autofac容器,该容器将传递一个服务列表以注册以供在多个项目中使用。

我已经有了一个基本容器构建器,它在许多属性中都具有所有必需的类型,但是我需要使用该基础从类中注入服务列表。

我有:

        private void buildAutofacContainer(IServiceCollection services, List<ServiceDescriptor> servicesToAdd)
    {
        var builder = new ContainerBuilder();
        builder.Register(x => new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddEnvironmentVariables()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .Build()).As<IConfigurationRoot>().SingleInstance();
        builder.RegisterType<LoggingInterceptor>();
        builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>();
        builder.RegisterType<ApplicationEngine>().As<IApplicationEngine>();
        builder.RegisterType<ApplicationSettings>().As<IApplicationSettings>();
        builder.RegisterType<PortalUnitOfWorkFactory>().As<IPortalUnitOfWorkFactory>();
        builder.RegisterType<DataConnectionService>().As<IDataConnectionService>();
        builder.Populate(services);
        this.Container = builder.Build();
    }

我正在尝试做的事情:

            servicesToAdd.ForEach(o =>
        {
            object concrete = o.ImplementationInstance;
            Type type = o.ImplementationType;
            builder.RegisterType<concrete>().As<type>();
        });

任何帮助将不胜感激

c# dependency-injection autofac
1个回答
0
投票

我不确定我是否正确理解你。如果目标是将服务描述符列表添加到Autofac容器/容器构建器,则可以将这些描述符填充到services中,因为IServiceCollection是服务描述符的集合。

    void BuildBaseContainer(IServiceCollection services, List<ServiceDescriptor> servicesToAdd)
    {
        foreach (var descriptor in servicesToAdd)
        {
            services.Add(descriptor);
        }

        var builder = new Autofac.ContainerBuilder();
        builder.Populate(servicesToAdd);
        this.Container = builder.Build();
    }

或者如果您的目标是将对象/实例注册为仅在运行时已知的类型,则可以使用非通用As方法并将类型传递给该方法:

// Could also use descriptor.ImplementationType depends on your ServiceDescriptor.
var concreteType = descriptor.ImplementationInstance.GetType();
builder.RegisterType(concreteType)
        .As(descriptor.ImplementationType) // As implementation type
        .As(<other type>) // As any other type
        .AsSelf() // As the object's type
        .As(descriptor.ImplementationInstance.GetType()) // As the implementation instance type
        .AsImplementedInterfaces() // As all implemented interface types
        ;
© www.soinside.com 2019 - 2024. All rights reserved.