question

BirisAris-0189 avatar image
0 Votes"
BirisAris-0189 asked ZhiLv-MSFT answered

Refactoring methods to controllers to DI-Container as a service

hope ur doing well, I'm trying to minimize the repetitive code, so I created methods for each controller, all works fine, now I want to create a new controller for the method and register it in the DI container but unfortunately the Di container doesn't pick it up :This exception was originally thrown at this call stack:

Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(System.IServiceProvider, System.Type)

Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(object, Microsoft.AspNetCore.Builder.IApplicationBuilder)
in services.AddTransient();

this is my method as a controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using QlikviewServer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using System.DirectoryServices.AccountManagement;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;


namespace QlikviewServer.Services
{
public class GetAZCredidentials //: IUserManager/IHttpContextAccessor<GetAZCredidentials>/<GetAZCredidentials>//GetAZCredidentials//IActionContextAccessor
{
private readonly GetAZCredidentials _context;
DbSet<ApplicationUser> ApplicationUsers;

     public HttpContext HttpContext { get => ((IHttpContextAccessor)_context).HttpContext; set => ((IHttpContextAccessor)_context).HttpContext = value; }

     //     public ActionContext ActionContext { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
     private readonly IServiceProvider services;
     public GetAZCredidentials(IServiceProvider services)
     {
         this.services = services;
     }
     public int  GetAZCredidentials1()
     {
           
             //  var person = GetPerson();

             PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
             UserPrincipal user1 = UserPrincipal.Current;

             string displayName2 = user1.DisplayName;

             string displayName = user1.SamAccountName;
             string DistinguishedName = user1.DistinguishedName;
             string[] values = DistinguishedName.Split(',');
             string domain = values[6];
             string[] values2 = domain.Split('=');
             string domain2 = values2[1].Trim();
             string UserPrincipalName2 = user1.UserPrincipalName;
             var comp = values[4];
             var company_id = comp.Split('=');
             var company_id2 = company_id[1].Trim();
             List<ApplicationUser> groupsad = (from m in _context.ApplicationUsers
                                               select new ApplicationUser { ApplicationUserId = m.ApplicationUserId, UserName = m.UserName, NameAdmin = m.NameAdmin, DisplayName = m.DisplayName, UserPrincipalName = m.UserPrincipalName }).ToList();




             var groups2 = (from m in _context.ApplicationUsers
                            select m).ToList();

             for (int i = 0; i < groupsad.Count; i++)
             {
                 if (string.IsNullOrEmpty(groupsad[i].NameAdmin.Trim()))
                 {
                     groupsad[i].NameAdmin = groupsad[i].NameAdmin.Trim();
                 }
                 if (string.IsNullOrEmpty(groupsad[i].UserName.Trim()))

                 {
                     groupsad[i].UserName = groupsad[i].UserName.Trim();
                 }


                 _context.ApplicationUsers.Where(it => it.NameAdmin == groupsad[i].NameAdmin).ToList()
                   .ForEach(
                        it =>
                        {

                            var it2 = it.NameAdmin.TrimEnd();

                            if (it2 == displayName)
                            {
                                it.DisplayName = displayName2;
                            }

                        }


                         );



                 if (string.IsNullOrEmpty(groupsad[i].UserPrincipalName.Trim()))
                 {

                     _context.ApplicationUsers.Where(it => it.NameAdmin == groupsad[i].NameAdmin).ToList()
                    .ForEach(
                         it =>
                         {

                             var it2 = it.NameAdmin.TrimEnd();

                             if (it2 == displayName)
                             {
                                 it.UserPrincipalName = UserPrincipalName2;
                             }
                         }
                             );

                 }
                 else
                 {
                     groupsad[i].UserPrincipalName = groupsad[i].UserPrincipalName.Trim();

                 }




                 var usersadmitted = (from m in _context.ApplicationUsers
                                      select new ApplicationUser { NameAdmin = m.NameAdmin, UserName = m.UserName }).ToList();
              //   ViewBag.ad = (from m in _context.ApplicationUsers
            //                   select new ApplicationUser { NameAdmin = m.NameAdmin }).ToList();

             }
             foreach (ApplicationUser f in groupsad)
             {
                 if (f.NameAdmin.Trim() == displayName)
                 {

                     if (f.UserName.Trim() == "reader" || f.UserName.Trim() == "admin" && domain2 == "Vionet")
                     {
             //            if (f.UserName.Trim() == "reader") { ViewBag.reader_admin = "reader"; }
             //            if (f.UserName.Trim() == "admin") { ViewBag.reader_admin = "admin"; }


                         return 1;


                     }
                 }
                 return 2;
             }
             return 3;
         }

       
 }

 public interface IUserManager
 {
 }

 public interface IHttpContextAccessor<T>
 {
 }

 public interface IActionContextAccessor<T>
 {
 }

}
and finally I call it if it would work as

var result1 = serviceProvider.GetRequiredService<GetAZCredidentials>();

         if (result1 != 1)
         {

thus depending on the return type 1,2,or 3 take appropriate action, any input will be highly appreciated as this my first refactoring, What's the exception you are getting? InvalidOperationException: No service for type 'Microsoft.Extensions.DependencyInjection.IServiceCollection' has been registered.thank you in advance

dotnet-aspnet-core-mvc
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

According to the IServiceProvider.GetRequiredService() documentation the InvalidOperationException exception is expected when the service is not registered. The GetAZCredidentials class shared above does not implement an interface. How did you register the service?

1 Vote 1 ·

im very sorry i didnt know i needed an interface, ill google on how to create an inteface and come back to u, thank you very much

0 Votes 0 ·
AgaveJoe avatar image AgaveJoe BirisAris-0189 ·

im very sorry i didnt know i needed an interface, ill google on how to create an inteface and come back to u

I think a better option is reading the dependency injection reference documentation. I recommend building a simple "Hello World" service to understand the basic pattern.

Dependency injection in ASP.NET Core


1 Vote 1 ·
Show more comments

1 Answer

ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered

Hi @BirisAris-0189,

When use Dependency injection in ASP.NET Core, after creating the service with/without the interface, we need to register the service with a lifetime in the ConfigureServices method (use the AddScoped(), AddTransient() and AddSingleton() method), like this:

 namespace Core3_1MVC.Services
 {
     public class Service1
     {
         public string GetAllStudent()
         {
             return "Students";
         }
     }
    
     public class Service2:IDisposable
     {
         private bool _disposed;
         public void Dispose()
         {
             if (_disposed)
                 return;
    
             Console.WriteLine("Service2.Dispose");
             _disposed = true;
         }
    
         public string GetAllStudent()
         {
             return "Students";
         }
     }
    
     public interface IService3Interface
     {
         string GetAllStatus();
     }
    
     public class Service3 : IService3Interface
     {
         public string GetAllStatus()
         {
             return "Status";
         }
     }
 }

Code in the ConfigureServices method:

     public void ConfigureServices(IServiceCollection services)
     { 
         services.AddScoped<Service1>();  
         services.AddScoped<Service2>();
         services.AddScoped<IService3Interface, Service3>();
         services.AddControllersWithViews(); 
     }

Then, access the services in the controller:

 public class HomeController : Controller
 {  
     private readonly IService3Interface _service3;
     private readonly Service1 _service1;
     private readonly Service2 _service2;
     public HomeController(IService3Interface service3Interface, Service1 service1, Service2 service2)
     { 
         _service3 = service3Interface;
         _service1 = service1;
         _service2 = service2;
     }
 
     public IActionResult Index()
     {
         var result1 = _service1.GetAllStudent();
         var result2 = _service2.GetAllStudent();
         var result3 = _service3.GetAllStatus(); 
         return View();
     }

More detail information, see:

Dependency injection in ASP.NET Core

Dependency injection into controllers in ASP.NET Core

Dependency injection into views in ASP.NET Core


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Best regards,
Dillion

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.