find and solve ||
Please wait.....

Dependency Injection .NET Core Unable to resolve-InvalidOperationException

When I am trying to use IServiceCollection in the startup.cs to resolve my dependencies. I'm injecting a depdency in my controller, and that depency is resolved to a class which also has an injected dependency. Basically I'm getting issue as "Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)"because it's unable to activate the dependency.


Option 1.

Create static class DependencyInjector like as give below

   public static class DependencyInjector
    {         public static IServiceCollection RegisterServiceDependencies(this IServiceCollection services, int i = 0)
            // repository
            //services.AddScoped<IMasterMenuProvider, MasterMenuProvider>();
            return services;

Call this service in your in Startup.cs  like as 

   public void ConfigureServices(IServiceCollection services)

Call your Service in your controller like as given below code

  public class MyControllerNameController : BaseController
        private readonly YourIServiceClass _iServiceClass
        public MyControllerNameController (YourIServiceClass iserviceClass)         {             _iServiceClass= iserviceClass;         }         public IActionResult Index()         {             return View();         }     } }

Hope this will address your problems.

Option 2.

Some time you will forget connection call in your Startup.css

services.AddDbContext<My_ScaffoldingContext>(options =>

Option 3.

In the some it will be also address this types of problem lilke as 

For some case your code sample in the same error was a result of a circular dependency.Check your circular dependency also.

Option 4.

May be forgot to register the type MyPropertiesRepository in your like ast:

     public void ConfigureServices(IServiceCollection services)
            services.AddSingleton<IMyPropertiesRepository, MyPropertiesRepository>()
            var connection = @"Server=(localdb)\mssqllocaldb;Database=Database_Name;Trusted_Connection=True;ConnectRetryCount=0";             services.AddDbContext<MyPropertiesContext>(options => options.UseSqlServer(connection));         }

Selena  Kandakar

Selena Kandakar

I like working on projects with a team that cares about creating beautiful and usable interfaces.

If felt valuable to you, feel free to share it.


Report Response