RegisterPerWebRequest 已过时,我可以使用 Lifestyle.Scoped 吗?

Rip*_*ppo 4 c# dependency-injection simple-injector

我只是在检查我的理智。这是我使用 simpleinjector 3.3.2 的代码

Container.RegisterPerWebRequest<HttpContextBase>(() =>
{
  var context = HttpContext.Current;
  if (context == null && Container.IsVerifying) return new FakeHttpContext();
    return new HttpContextWrapper(context);
});


Container.Verify();
Run Code Online (Sandbox Code Playgroud)

...

    public class FakeHttpContext : HttpContextBase { }
Run Code Online (Sandbox Code Playgroud)

然而,RegisterPerWebRequest 现在被标记为已过时,我不能 100% 确定这是否是更改代码以反映新代码库的正确方法。

Container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

//So we can inject HttpContextBase into any class
Container.Register<HttpContextBase>( () =>
{
  var context = HttpContext.Current;
  if (context == null && Container.IsVerifying)
    return new FakeHttpContext();

  return new HttpContextWrapper(context);
}, Lifestyle.Scoped);
Run Code Online (Sandbox Code Playgroud)

所以我的问题是“我应该使用Lifestyle.Scoped替换RegisterPerWebRequest吗?我仍然可以按原样使用代码吗?


从文档来看我应该做得正确

Ste*_*ven 5

您显示的代码是正确的。Container.Register<T>(Func<T>, Lifestyle.Scoped)取代Container.RegisterPerWebRequest<T>(Func<T>).