And how can I transfer services from Dependancy Injection that are registered in startup.cs in an ASP.NET MVC Core application to classes other than the controller class?

Did I understand correctly that they need to be manually thrown over there, since static methods and variables are an old ideology, and it is no longer supported in ASP.NET MVC Core and IoC is designed to replace it?

UPDATED: I do a database initializer, and I think from where in it to take ApplicationDbContext and UserManager

public static class DbInitializer { public static async void Initialize(ApplicationDbContext db, UserManager<ApplicationUser> userManager,RoleManager<IdentityRole> roleManager) { if(db.Users.Count() == 0 && db.Roles.Count() == 0) { ApplicationUser user1 = new ApplicationUser() { UserName = "Admin", Age = 30 }; await userManager.CreateAsync(user1,"password"); //... } } } 

Class sturtup.cs

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,ApplicationDbContext db, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) { //... DbInitializer.Initialize(db, userManager, roleManager); } 

While I am doing this, but I think I can DbInitializer get the necessary services right away from DbInitializer .

  • add sample code. it's not entirely clear what you mean - Grundy
  • @Grundy added - Dmitry Polyanin

1 answer 1

Like your code can be called the correct implementations but this code can be improved.
hard code dependency is evil
I would implement it like this:
if there is no admin then redirect to register or throw "ApplicationNotConfiguredException" and indicate in the documentation that you need to create a user in the database.
but that's not the point
such classes will be needed in the context of the controller.
you, use abstract types (intefaces, abstract classes) and keep in mind that Kanche Kanche will call these classes in the controller. The point is that the controller should call your additional functional classes and God bless you by giving 3 ways to implement dependencies.
because the controller is the main building block of your applications.
without it there is no life for other classes
if it is not for you then you mean not MVC.