Martin Staufcik
Martin Staufcik

Reputation: 9490

ASP.NET Core DI access container directly

Is there a way of accessing the DI container of ASP.NET Core directly from a class?

Usually what is done is constructor injection:

public class ProductsController : Controller
{
    public ProductsController(ISomeService service)
    {

    }
}

Instead, I would like to do something like:

var service = ServiceLocator.GetService<ISomeService>();

For some services I would not like to use the default constructor injection, but rather get the service directly from the container.

Upvotes: 3

Views: 1509

Answers (1)

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16811

It's called the Service locator pattern and can be done by injecting the IServiceProvider

public class ProductsController : Controller
{
    public ProductsController(IServiceProvider services)
    {
        var service = services.GetService<ISomeService>(); 
    }
}

Here's a good article which goes throw the different strategies

Upvotes: 3

Related Questions