简体   繁体   English

带上下文的Asp.net核心DI

[英]Asp.net core DI with context

I'm trying implement a simple dependency (in ASP.NET Core) as this: 我正在尝试实现一个简单的依赖项(在ASP.NET Core中),如下所示:

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. 问题是TempDataDictionary依赖于此控制器中存在的HttpContext的事实。 How to implement that scenario in DI, since the ServiceLocator has no knowledge of HttpContext at Startup? 由于ServiceLocator在启动时不了解HttpContext ,因此如何在DI中实现该方案?

As this? 这样吗

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

But where i fill the constructor parameter HttpContext if this present just in controller? 但是,如果HttpContext在于控制器中,我在哪里填充构造函数参数HttpContext

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) 在Startup.cs(ConfigureServices)中

services.AddScoped<AppStateService>();

In your controller 在您的控制器中

public class TestController : Controller
{

    protected readonly CompanyRepository _companyRepository;

    public TariffsController(AppStateService appStateService)
    {
        _appStateService = appStateService;
    } 
}

you can take a dependency on IHttpContextAccessor and register it with DI 您可以依赖IHttpContextAccessor并向DI注册

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

then use it to get the HttpContext 然后使用它来获取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 但是在控制器中,您可以直接访问HttpContext,所以我不清楚为什么要在此注入它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM