我有一个 asp.net MVC 站点,其中有许多使用 InstancePerHttpRequest 范围注册的组件,但是我还有一个“后台任务”,它将每隔几个小时运行一次,但不会有 httpcontext。
我想获得一个已像这样注册的 IRepository 实例
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
.InstancePerHttpRequest();
如何使用 Autofac 从非 http 上下文执行此操作?我认为 IRepository 应该使用 InstancePerLifetimeScope
有几种方法可以做到这一点:
-
我认为最好的一个。正如您所说,您可以将存储库注册为 InstancePerLifetimeScope。它同样适用于 HttpRequests 和 LifetimeScopes。
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
.InstancePerLifetimeScope();
-
您对 HttpRequest 的注册可能与 LifetimeScope 的注册不同,那么您可以进行两个单独的注册:
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
.WithParameter(...)
.InstancePerHttpRequest(); // will be resolved per HttpRequest
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
.InstancePerLifetimeScope(); // will be resolved per LifetimeScope
-
您可以显式创建"HttpRequest"
使用其标签的范围。暴露通过MatchingScopeLifetimeTags.RequestLifetimeScopeTag
新版本中的属性。
using (var httpRequestScope = container.BeginLifetimeScope("httpRequest")) // or "AutofacWebRequest" for MVC4/5 integrations
{
var repository = httpRequestScope.Resolve<IRepository<Entity>>();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)