How to get an instance in . net core without using constructor

Asked

Viewed 34 times

1

Normally I use the constructor to get dependencies something like:

public class Test
{
    private IServiceDependency serviceDependency;
    Test(IServiceDependency serviceDependency)
    {
         _serviceDependency = serviceDependency;
    }
}

How do I get dependency without using the constructor GetDependence(); is just a method to illustrate how you would like to get dependency on . net core

 public class Test
 {
     private IServiceDependency serviceDependency;
     Test()
     {
        _serviceDependency = GetDependence();
     }
 }
  • Saw the answer?

  • Didn’t you see? asked and there’s no interaction?

1 answer

1


His example does not match the reality of Dependency Injection that can happen in the case . NET Core in two ways, by the constructor or by the method, the first already knows how the other works is with [Fromservices] preceding the settings of a method in the declaration of variables, for example:

public IActionResult Create([FromServices] IServiceDependency dependency) 
{
    dependency....
}

This type of resource can be used for one or several dependency injections that is required for your code.

Reference: Dependency Injection into controllers in ASP.NET Core

Browser other questions tagged

You are not signed in. Login or sign up in order to post.