亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將類注冊為接口但調用方法?

如何將類注冊為接口但調用方法?

C#
胡說叔叔 2023-07-23 16:51:43
我復制了下面的代碼,它工作得很好,但我已經修改了它以滿足我的需要,通過將 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){? ? ...}因為我已經添加了接口并且它具有相同的前綴&ldquo;設置&rdquo;,所以它選擇了我不想要的接口,而是我想將它與相應的類一起使用?我正在嘗試執行此操作(但使用上面的語法,因為我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();

    });


查看完整回答
反對 回復 2023-07-23
  • 1 回答
  • 0 關注
  • 131 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號