[SOLVED] Why I am Getting Same Error While Starting Application ? "InvalidOperationException: Unable to resolve service"


Error =>

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type ‘Business_Logic_Layer.Home.IHomeBLL’ while attempting to activate ‘BookReadingEventWebApplication.Controllers.HomeController’.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Startup.cs =>

 public void ConfigureServices(IServiceCollection services)
            services.AddDbContext<ApplicationDbContext>(options =>

            services.AddIdentity<IdentityUser, IdentityRole>()

            services.AddScoped<IAccountRepository, AccountRepository>();



  [1]: https://i.stack.imgur.com/39YUb.png

**HomeController** =>

 public class HomeController : Controller
        private readonly ILogger<HomeController> _logger;

        public readonly IHomeBLL _BLL;

        public HomeController( ILogger<HomeController> logger, IHomeBLL BLL)
            _logger = logger;
            _BLL = BLL;

        public IActionResult Index()
            var list = _BLL.GetAllEvents();
            return View(list);

**HomeBLL** =>

public class HomeBLL : IHomeBLL
        private Data_Access_Layer.HomeDAL _DAL;

        public HomeBLL(Data_Access_Layer.HomeDAL DAL)
            _DAL = DAL;

        public List<BookReadingEventModel> GetAllEvents()
            return _DAL.GetAllEvents();

**IHomeBLL** =>

public interface IHomeBLL
        public List<BookReadingEventModel> GetAllEvents();


You need to registers IHomeBLL service in ConfigureServices.

For example:

// or AddSingleton or AddTransient
services.AddScoped<IHomeBLL, HomeBLL>();

However, since HomeBLL depends on (Data_Access_Layer.HomeDAL DAL) and you’ll need to follow this chain.

Registering HomeDAL

You’re not showing what HomeDAL needs to be created the following is guesswork.

Here are some options, and one may be applicable to you setup.

If HomeDAL needs to be created ‘by hand’:

// Create 
HomeDAL homeDAL = ...;
services.AddScoped<IHomeBLL>(provider => new HomeBLL(homeDAL));

Please note that it could be better if HomeDAL implemented an interface IHomeDAL and HomeBLL depened on IHomeDAL. Then if HomeDAL doesn’t have any dependencies you could register both of them the following way:

// or AddSingleton or AddTransient
services.AddScoped<IHomeDAL, HomeDAL>();
services.AddScoped<IHomeBLL, HomeBLL>();

Answered By – tymtam

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *