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

如何将实现多接口的服务注入到类中?

构造注入实现两个接口的单例服务

你配置的服务注册是没问题的,构造注入完全可以正常工作,只需根据业务需求选择注入的类型:

  • 注入具体类SweetAlert:如果需要同时调用两个接口的所有方法,直接注入具体类即可
public class YourService
{
    private readonly SweetAlert _sweetAlert;

    public YourService(SweetAlert sweetAlert)
    {
        _sweetAlert = sweetAlert;
    }

    public void DoSomething()
    {
        // 调用ISweetAlert的方法
        _sweetAlert.ShowSuccess();
        // 调用ISweetAlert2的方法
        _sweetAlert.ShowCustomDialog();
    }
}
  • 注入ISweetAlert接口:如果只需要用到ISweetAlert定义的方法,注入该接口
public class YourService
{
    private readonly ISweetAlert _sweetAlert;

    public YourService(ISweetAlert sweetAlert)
    {
        _sweetAlert = sweetAlert;
    }

    public void ShowSuccessAlert()
    {
        _sweetAlert.ShowSuccess();
    }
}
  • 注入ISweetAlert2接口:同理,仅需要ISweetAlert2的方法时注入该接口
public class YourService
{
    private readonly ISweetAlert2 _sweetAlert2;

    public YourService(ISweetAlert2 sweetAlert2)
    {
        _sweetAlert2 = sweetAlert2;
    }

    public void ShowCustomAlert()
    {
        _sweetAlert2.ShowCustomDialog();
    }
}
  • 同时注入两个接口:如果业务逻辑需要分别通过两个接口调用方法,也可以同时注入两个接口(实际指向同一个单例实例)
public class YourService
{
    private readonly ISweetAlert _sweetAlert;
    private readonly ISweetAlert2 _sweetAlert2;

    public YourService(ISweetAlert sweetAlert, ISweetAlert2 sweetAlert2)
    {
        _sweetAlert = sweetAlert;
        _sweetAlert2 = sweetAlert2;
    }

    public void HandleAlerts()
    {
        _sweetAlert.ShowSuccess();
        _sweetAlert2.ShowCustomDialog();
    }
}

你的注册代码已经确保所有注入方式拿到的都是同一个SweetAlert单例实例,不存在常规构造注入失效的问题,只需根据实际需求选择合适的注入类型即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:00:16