You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Autofac中注册实现多接口的类型?配置类注册疑问咨询

Great question! Let's break this down clearly.

First, your current registration approach won't give you a single shared instance of Config across both interfaces—here's why: each RegisterType<Config>() call creates a separate component registration in Autofac. Even though both are marked SingleInstance(), each registration will spin up its own unique instance of Config when first resolved for their respective interfaces. That's almost certainly not what you want, since you likely want the same config object used everywhere in your app.

The good news is there's a clean, correct way to register your Config class once so it resolves as both ISettingsConfig and IStorageConfig using a single instance:

builder.RegisterType<Config>()
       .As<ISettingsConfig>()
       .As<IStorageConfig>()
       .SingleInstance();

This tells Autofac: "Create one instance of Config, and when someone asks for ISettingsConfig or IStorageConfig, give them this exact same instance."

When your SettingsHandler and StorageHandler are resolved, Autofac will inject the same Config instance into both, since both depend on interfaces mapped to the same singleton registration.

If you ever add more interfaces that Config implements, you can just chain another .As<INewConfig>() to this same registration instead of adding a whole new RegisterType line—much cleaner and eliminates the risk of accidental multiple instances.

Just to confirm: your handler classes (SettingsHandler and StorageHandler) are set up correctly. Since they accept their respective config interfaces and share the same ApiClient dependency, Autofac will resolve those properly once the config registration is fixed.

内容的提问来源于stack exchange,提问作者r3plica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:10:36