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

.NET Core 2.0如何创建自定义类单例并注入?解决服务未注册报错

解决.NET Core 2.0控制台应用中Services类注入失败的问题

你遇到的'No service for type 'Services' has been registered.'错误原因很直白——你没把Services类注册到依赖注入容器里,而且它依赖的DbContext也得先完成注册,不然注入时还会踩新坑。另外你要求把Services做成单例,咱们一步步来修正:

1. 先注册依赖的DbContext

Services的构造函数依赖DbContext,所以得先把你的具体DbContext(比如假设是AppDbContext,替换成你实际的DbContext类名)注册到服务容器。在.NET Core 2.0里用AddDbContext方法:

// 替换成你的数据库连接字符串和DbContext类型
services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=YourDatabase;Trusted_Connection=True;"));

如果你的Services里直接用的是基类DbContext(不推荐,建议用具体派生类),那注册时要对应写成services.AddDbContext<DbContext>(...),但还是用具体类更清晰,避免注入歧义。

2. 把Services注册为单例

接下来将Services以单例生命周期添加到容器,用AddSingleton方法:

services.AddSingleton<Services>();

这样容器就知道如何创建Services实例,并且会全程复用这一个实例。

3. 完整的Program类示例代码

把这些步骤整合后,你的Program类代码大概是这样:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        var services = new ServiceCollection();

        // 注册DbContext
        services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer("你的数据库连接字符串"));

        // 注册Services为单例
        services.AddSingleton<Services>();

        // 注册Main类
        services.AddTransient<Main>();

        // 构建服务提供者
        var serviceProvider = services.BuildServiceProvider();

        // 获取Main实例并使用
        var main = serviceProvider.GetService<Main>();
        main.RunLogic(); // 假设Main里有调用Services的业务方法
    }
}

额外注意事项

  • 如果你坚持用单例的Services,要注意默认DbContext是Scoped生命周期,单例依赖Scoped服务会导致DbContext无法正确释放(因为单例生命周期更长)。这种情况下要么把DbContext也改成单例(适合简单场景,注意并发问题),要么调整Services的生命周期为Scoped/Transient:
    // 将DbContext设为单例
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer("你的连接字符串"), ServiceLifetime.Singleton);
    

调整完这些,那个注册错误就会消失,Services也能被正确注入到Main类里使用了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:15:54