1

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?

3
  • Is this an Instanced Sql Server Install or default? Pretty sure your connection string is wrong Commented Dec 29, 2018 at 22:10
  • @mvermef i didnt install any Sql Server Commented Dec 30, 2018 at 5:37
  • 1
    Then how in heck do you plan on this working? Kinda need it to have this work, since that what you are telling it to connect to with whole configuration, MD\\MD is what then? Commented Dec 30, 2018 at 6:19

2 Answers 2

2

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")));
Sign up to request clarification or add additional context in comments.

3 Comments

Im Getting Error as Unable to resolve service for type 'MVC_Core.ConnectionString.ConnectToDb' while attempting to activate 'MVC_Core.Business.Repo'
@JOHNMickh I'm trying to find potential problems with DbContext registration but can't find anything. You can register ConnectToDb directly as a service with services.AddScoped<ConnectToDb>(); but it'll be workaround for the real problem. Is there any additional info about exception?
@VadimMartynov Have you changed services.AddDbContext<DbContext> to services.AddDbContext<ConnectToDb>? Share us your current startup.cs.
0

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")));

1 Comment

Im Getting Error as Unable to resolve service for type 'MVC_Core.ConnectionString.ConnectToDb' while attempting to activate 'MVC_Core.Business.Repo'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.