Dependency Injection

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.

Plugin Manager fully supports this type of plugin, during the initialisaton phase individual plugins can register services via the IServiceCollection, which can then be used by the host application, or other plugins.

How it Works

This method is slightly different than the other native plugin types. We create a lightweight library who's only purpose is to contain interfaces and/or abstract classes.

This library is referenced by the plugin which implements the interface or abstract class, and is also responsible for registering the interface with the IServiceCollection instance for the host application.

dependency injection

Example Memory Cache Plugin

The source control contains a sample plugin which implements an IMemoryCache object. The interface is registered within the SharedPluginFeatures library.

The plugin implements 3 methods:

  • GetShortCache. Returns a cache which has a default lifetime of 5 minutes.
  • GetCache. Returns a Cache which has a default lifetime of 2 hours.
  • ResetCaches. Clears all caches of all data.

Although their are default lifetimes, these can be overridden within appsettings.json.

When the class is initialised, it registers the IMemoryCache interface as a service for DI.

public void ConfigureServices(IServiceCollection services)
services.AddSingleton<IMemoryCache, MemoryCache>();

Controllers can then get the IMemoryCache instance when being created, and take advantage of the IMemoryCache instance to add or get cached data.

public class HomeController : Controller
#region Private Members

private readonly IMemoryCache _memoryCache;

#endregion Private Members

#region Constructors

public HomeController(IMemoryCache memoryCache)
// Memory Cache is initialised during the Plugin Manager and set to be injected in using DI
_memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));

#endregion Constructors