简体   繁体   English

尝试连接到SQL Server数据库时出现错误

[英]Getting Error While trying to connect to a SQL Server database

I'm new to .NET Core. 我是.NET Core的新手。 While I'm connecting to a SQL Server database, I'm getting an error: 当我连接到SQL Server数据库时,出现错误:

Unable to resolve service for type 'MVC_Core.Business.Repo' while attempting to activate 'MVC_Core.Controllers.AbcController 尝试激活“ MVC_Core.Controllers.AbcController”时无法解析“ MVC_Core.Business.Repo”类型的服务

My StartUp.cs : 我的StartUp.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
    services.AddTransient<IRepo,Repo>();
}

Application.js : Application.js

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    },
    "ConnectionStrings": {
      "BloggingDatabase": "Data Source=MD\\MD;Initial Catalog=Ems_local;User ID=sa;Password=123"
    }
  },
  "AllowedHosts": "*"
}

My DbContext : 我的DbContext

public class ConnectToDb : DbContext
{
        //public DbConnection(){}

        public ConnectToDb(DbContextOptions<ConnectToDb> options) : base(options)
        {
        }

        public virtual DbSet<Country> Country { get; set; }
    }

This connection I'm calling like this: 我这样调用此连接:

public class Repo : IRepo
{
        private ConnectToDb db = null;

        public Repo(ConnectToDb _db)
        {
            db = _db;
        }

While I'm calling this in my controller as 当我在控制器中将此称为

Repo ObjRepo;

public AbcController(Repo _objRepo)
{
    ObjRepo = _objRepo;
}

[Route("Hello")]
public IActionResult Index()
{
    var x = ObjRepo.GetCountry();
    return Json("abc" + x);
}

Please guide me - why am I getting this error? 请指导我-为什么我会收到此错误?

You have two problems with dependency injection in ASP.NET Core . 在ASP.NET Core中依赖项注入存在两个问题。

When you call AddTransient method you add new service of the type specified in the first type parameter with an implementation type specified in the second one. 调用AddTransient方法时,将添加第一个type参数中指定类型的新服务和第二个中指定的实现类型。 It allows you to use service as an dependency without specifying its implementation. 它允许您将服务用作依赖项,而无需指定其实现。

You've registered class Repo as an implementation for the interface IRepo and then should use interface to resolve it: 您已经 Repo注册IRepo接口的IRepo ,然后应使用interface来解决它:

public AbcController(IRepo _objRepo)

Aslo, AddDbContext is an extension method for registration DbContext and EF infrastructure as a service and it works in the same way. AddDbContextAddDbContext是用于将DbContext和EF基础结构注册为服务的扩展方法,并且其工作方式相同。 Here is an important part of the implementation for your example: 这是示例实现的重要部分:

// TContextService is the type parameter
serviceCollection.TryAdd(new ServiceDescriptor(typeof(TContextService), typeof(TContextService), ServiceLifetime.Scoped));

It means that in the serviceCollection adds new service of the type TContextService with implementation type TContextService . 这意味着,在serviceCollection添加类型的新服务TContextService与实现类型TContextService

So, you should fix registration for your DbContext with specific class name as a generic parameter to resolve it in class Repo : 因此,您应该使用特定的类名将DbContext注册修复为通用参数,以在Repo类中解决该问题:

services.AddDbContext<ConnectToDb>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));

Your registration is with IRepo. 您的注册是通过IRepo。 You need to chang below code from Repo to IRepo 您需要将以下代码从Repo更改为IRepo

IRepo ObjRepo;
public AbcController(IRepo _objRepo)
{
    ObjRepo = _objRepo;
}

besides you need to use ConnectToDb DbContext as interface when you are registering your DbContext 此外,在注册DbContext时还需要使用ConnectToDb DbContext作为接口

 services.AddDbContext<ConnectToDb>(options => options.UseSqlServer(
    Configuration.GetConnectionString("BloggingDatabase")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM