Dependency Injection

Dependency Injection is an important part of how .Net 6 and ASP.Net Core functions. The .Net 6 version of Relatude introduces some new classes to use with DI.

Controllers, filters or middleware

 By specifying any of the services configured in Program.cs, in the constructor of a controller, middleware or filter, it will be injected when it is created. This makes the code more testable, and easier to swap implementations. 

public ArticleController(WAFNativeContext ctx) {

 You can also use dependency injection in one specific action in a controller by adding a [FromServices] attribute on the parameter you want to be injected:

public IActionResult About([FromServices] IExampleProvider exampleProvider)

Get services without DI

While Dependency Injection is a very good tool, sometimes you want to access the services without using dependency injection. If you are in a web context, you can do that easily by calling the RequestServices method on the HttpContext object:

var ctx = context.RequestServices.GetService(typeof(WAFNativeContext));

WAFNativeContext

The WAFNativeContext object is more or less a replacement of the WAFContext object in the .Net Framework version of Relatude that can be injected in your projects to get access to most of the same APIs. It is is made available for injection when the following line is added in Program.cs:

 

builder.AddWAFNativeContext();