0

I have been looking at controller classes in .NET Core with constructors that take IMemoryCache arguments but cannot see where the passed objects come from originally. For instance, this example declaration from Cache in-memory in ASP.NET Core:

public class HomeController : Controller
{
    private IMemoryCache _cache;

    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }
}

Where would this constructor be called and how is the IMemoryCache object instantiated in the first place? Is this something that happens behind the scenes with .NET Core that does not have to be coded explicitly? I have seen similar examples using an ILogger object, so my question would also apply to that.

1 Answers1

1

The instance is created on startup and registered in the DI container. Then, at runtime when objects are created their dependencies are injected by this container. This whole pattern is called "dependency injection". It decouples your classes from concrete implementations and allow you to mock the dependencies when writing tests. You can read more about dependency injection and the default DI container in ASP.NET Core here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0. You can also read more about the Dependency inversion principle. (D in SOLID)

Also, I can recommend you to read the book "Dependency injection in .NET" by Mark Seeman for a deeper understanding of this pattern. You can also check this SO post.

Lyubomir Ruzhinski
  • 173
  • 1
  • 2
  • 7