簡體   English   中英

嘗試連接到SQL Server數據庫時出現錯誤

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

我是.NET Core的新手。 當我連接到SQL Server數據庫時,出現錯誤:

嘗試激活“ MVC_Core.Controllers.AbcController”時無法解析“ MVC_Core.Business.Repo”類型的服務

我的StartUp.cs

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

Application.js

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

我的DbContext

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

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

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

我這樣調用此連接:

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

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

當我在控制器中將此稱為

Repo ObjRepo;

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

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

請指導我-為什么我會收到此錯誤?

在ASP.NET Core中依賴項注入存在兩個問題。

調用AddTransient方法時,將添加第一個type參數中指定類型的新服務和第二個中指定的實現類型。 它允許您將服務用作依賴項,而無需指定其實現。

您已經 Repo注冊IRepo接口的IRepo ,然后應使用interface來解決它:

public AbcController(IRepo _objRepo)

AddDbContextAddDbContext是用於將DbContext和EF基礎結構注冊為服務的擴展方法,並且其工作方式相同。 這是示例實現的重要部分:

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

這意味着,在serviceCollection添加類型的新服務TContextService與實現類型TContextService

因此,您應該使用特定的類名將DbContext注冊修復為通用參數,以在Repo類中解決該問題:

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

您的注冊是通過IRepo。 您需要將以下代碼從Repo更改為IRepo

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

此外,在注冊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