【发布时间】:2016-02-19 20:21:26
【问题描述】:
当我尝试在同一请求中的 2 个中间件中访问它时,出于某种原因,我的作用域服务似乎正在生成同一类的不同实例。
场景:我正在添加这样的范围服务:
public interface ISimplyRecorder
{
void AddInfo(string key, string value);
Dictionary<string, string> GetAllInfo();
}
public class SimplyCoreRecorderService : ISimplyRecorder
{
private Dictionary<string,string> data;
public SimplyCoreRecorderService()
{
data = new Dictionary<string, string>();
}
public void AddInfo(string key,string value)
{
data.Add("",value);
}
public Dictionary<string,string> GetAllInfo()
{
return data;
}
}
然后是startup.cs中的以下内容
services.AddScoped<ISimplyRecorder,SimplyRecorderService>();
现在我在示例中间件的构造函数中调用此服务。我可以使用新实例访问服务并向其中添加数据,然后调用 await _next(context)。但是,当我在我的 HomeController 中调用服务时,MVC 遵循上面的中间件,我似乎得到了一个新的服务实例,即使它是同一个请求。
家庭控制器:
ISimplyRecorder _simply;
private IHostingEnvironment _env;
public HomeController(IHostingEnvironment env,ISimplyRecorder simply)
{
_simply = simply;
_env = env;
}
public IActionResult Index()
{
_simply.AddInfo("Home:Action","resulted in index action");
return View();
}
如果有人想试一试,请访问:https://github.com/muqeet-khan/SimplyCore 获取完整代码。
【问题讨论】:
标签: asp.net-core asp.net-core-mvc