我復制了下面的代碼,它工作得很好,但我已經修改了它以滿足我的需要,通過將 I 添加到當前名稱來創建一個具有DatabaseSettings相同UserSettings后綴的接口。但問題是它試圖將接口注冊為接口,這是錯誤的?在進行更改之前,settings變量只有兩個條目,現在我已經添加了接口,settings正在拾取接口(因為后綴),因此它現在具有條目,而不是將它們添加為條目,我想將它們與相應的類一起使用并仍然調用.LoadSection(type)public class SettingsModule : Module{? ? private readonly string _configurationFilePath;? ? private readonly string _sectionNameSuffix;? ? public AeSettingsModule(string configurationFilePath, string sectionNameSuffix = "Settings")? ? {? ? ? ? _configurationFilePath = configurationFilePath;? ? ? ? _sectionNameSuffix = sectionNameSuffix;? ? }? ? protected override void Load(ContainerBuilder builder)? ? {? ? ? ? var settings = Assembly.Load(nameof(DataLayer))? ? ? ? ? ? .GetTypes()? ? ? ? ? ? .Where(t => t.Name.EndsWith(_sectionNameSuffix, StringComparison.InvariantCulture))? ? ? ? ? ? .ToList();? ? ? ? ?settings.ForEach(type =>? ? ? ? ?{? ? ? ? ? ? ?builder.Register(c => c.Resolve<ISettingsReader>().LoadSection(type))? ? ? ? ? ? ?.As(type)? ? ? ? ? ? ?.SingleInstance();? ? ? ? ?});? ? }}public class DatabaseSettings: IDatabaseSettings{? ? public string ConnectionString { get;? set; }? ? public int TimeoutSeconds { get; set; }}public interface IDatabaseSettings{? ? string ConnectionString { get; set; }? ? int TimeoutSeconds { get; set; }}我收到的錯誤消息是:`System.MissingMethodException: 'Cannot create an instance of an interface.'`因為我已經將`構造函數注入從類更改為接口:public UserService(IDatabaseSettings databaseSettings, IUserSettings userSettings){? ? ...}因為我已經添加了接口并且它具有相同的前綴“設置”,所以它選擇了我不想要的接口,而是我想將它與相應的類一起使用?我正在嘗試執行此操作(但使用上面的語法,因為我LoadSection也想調用):builder.RegisterType<DatabaseSettings>().As<IDatabaseSettings>();
1 回答

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
我通過反復試驗找到了一個解決方案,該應用程序按預期工作,但我不確定它是否高效、可靠等。
我發帖只是為了獲得反饋,如果它有效,其他人也許可以使用它。
var settings = Assembly.Load(nameof(DataLayer))
.GetTypes()
.Where(t => t.Name.EndsWith(_sectionNameSuffix, StringComparison.InvariantCulture ) && !t.IsInterface)
.ToList();
settings.ForEach(type =>
{
builder.Register(c => c.Resolve<ISettingsReader>().LoadSection(type))
.As(type.GetInterfaces())
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
});
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報
0/150
提交
取消