The ASP.NET 5 context works much differently than ASP.NET 4.6.1. HttpContext is accessed through the IHttpContextAccessor interface using dependency injection. Keep in mind, this information is openly published in the .NET 5 fundamental documentation. Below is an example that uses standard constructor injection loosely based on your code example..
public interface IContainer
{
string Name { get; set; }
}
public class Container : IContainer
{
public string Name { get; set; }
}
public interface IServiceLocator
{
IContainer Get();
void Set(IContainer container);
}
public class ServiceLocator : IServiceLocator
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ServiceLocator(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void Set(IContainer container)
{
_httpContextAccessor.HttpContext.Items.Add("__Container__", container);
}
public IContainer Get()
{
return (IContainer)_httpContextAccessor.HttpContext.Items["__Container__"];
}
}
Register the service in the startup.cs file
services.AddScoped<IServiceLocator, ServiceLocator>();
Constructor injection and implementation
public class DiDemoController : Controller
{
public readonly IServiceLocator _service;
public DiDemoController(IServiceLocator service)
{
_service = service;
}
public IActionResult Index()
{
Container container = new Container() { Name = "Hello World" };
_service.Set(container);
ViewBag.Name = _service.Get().Name;
return View();
}
}
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<div>@(ViewBag.Name ?? "Empty") </div>