我有一个 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>>(); }
关于asp.net - 为后台线程配置 Autofac 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896002/