0

I'm trying implement a simple dependency (in ASP.NET Core) as this:

public partial class BaseController : Controller
{
    public new ITempDataDictionary TempData { get; private set; }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        base.OnActionExecuting(context);

        //preparação da tempdata
        this.TempData = new TempDataDictionary(HttpContext); //todo: DI?
        this.TempData.Load();
    }
}

}

The problem is the fact TempDataDictionary depends of HttpContext present in this controller. How to implement that scenario in DI, since the ServiceLocator has no knowledge of HttpContext at Startup?

As this?

services.AddScoped(); //??????

But where i fill the constructor parameter HttpContext if this present just in controller?

  • Prevent letting your application components take a direct dependency on `HttpContext`, as described [here](https://stackoverflow.com/questions/30055268/how-to-get-microsoft-aspnet-http-httpcontext-instance-in-class-constructor-using/30057522#30057522) – Steven Dec 16 '16 at 07:16

2 Answers2

1

You should create a service to handle your state data and add it as scoped.

public class AppStateService
{ 
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ITempDataProvider _tempDataProvider;
    private IDictionary<string, object> _data;
    public AppStateService(IHttpContextAccessor httpContextAccessor, ITempDataProvider tempDataProvider, UserManager<EntsogUser> userManager, CompanyRepository companyRepository)
    {
        _httpContextAccessor = httpContextAccessor;
        _tempDataProvider = tempDataProvider;
        _data = _tempDataProvider.LoadTempData(_httpContextAccessor.HttpContext);
    }

    private void SetValue(string name, object value)
    {
        _data[name] = value;
        _tempDataProvider.SaveTempData(_httpContextAccessor.HttpContext,_data);
    }

    private object GetValue(string name)
    {

        if (!_data.ContainsKey(name))
            return null;
        return _data[name];
    }
}

In Startup.cs (ConfigureServices)

services.AddScoped<AppStateService>();

In your controller

public class TestController : Controller
{

    protected readonly CompanyRepository _companyRepository;

    public TariffsController(AppStateService appStateService)
    {
        _appStateService = appStateService;
    } 
}
EricImhauser
  • 701
  • 2
  • 7
  • 17
0

you can take a dependency on IHttpContextAccessor and register it with DI

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

then use it to get the HttpContext

However in a controller you have direct access to HttpContext so it isn't clear to me why you would want to inject it there

Joe Audette
  • 35,330
  • 11
  • 106
  • 99