JOHN Mickh
JOHN Mickh

Reputation: 35

Getting Error While trying to connect to a SQL Server database

I'm new to .NET Core. While I'm connecting to a SQL Server database, I'm getting an error:

Unable to resolve service for type 'MVC_Core.Business.Repo' while attempting to activate 'MVC_Core.Controllers.AbcController

My 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": "*"
}

My 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?

Upvotes: 1

Views: 111

Answers (2)

Vadim Martynov
Vadim Martynov

Reputation: 8902

You have two problems with dependency injection in 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. 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:

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. 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.

So, you should fix registration for your DbContext with specific class name as a generic parameter to resolve it in class Repo:

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

Upvotes: 2

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30663

Your registration is with IRepo. You need to chang below code from Repo to IRepo

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

besides you need to use ConnectToDb DbContext as interface when you are registering your DbContext

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

Upvotes: 0

Related Questions