【发布时间】:2014-10-27 11:27:52
【问题描述】:
我在基本级别使用 autofac 来处理依赖注入。我现在的配置很简单:
builder.RegisterType<TestDbContext>().As<DbContext, TestDbContext>().InstancePerRequest();
builder.RegisterType<UserRepository>().As<IUserRepository>().InstancePerRequest();
builder.RegisterType<TestRepository>().As<ITestRepository>().InstancePerRequest();
我的问题有点与:'Autofac Circular Component Dependency Detected' Error
我不想得到 Curcular 组件依赖错误,所以我不将 IUserRepository 包含到 ITestRepository 构造函数中(它包含在相反的方向)。
我想使用上述问题答案中的第二个建议。如何对我的TestRepository 进行编码以按需使用UserRepository?我尝试使用 BeginLifetimeScope 进行以下尝试:
public class TestRepository : ITestRepository
{
public TestRepository()
{
}
public void Test()
{
using (var scope = AutofacConfig.Container.BeginLifetimeScope())
{
var scopeUserRepo = scope.Resolve<IUserRepository>();
}
}
}
但我得到以下异常:
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the
instance was requested. This generally indicates that a component registered as
per-HTTP request is being requested by a SingleInstance() component (or a similar
scenario.) Under the web integration always request dependencies from the
DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the
container itself.
【问题讨论】:
-
您也可以尝试在 Autofac 中使用 Func 支持:所以在您的
public TestRepository(Func<IUserRepository> userRepositoryCreator)和您的Test()方法中只需写:var scopeUserRepo = userRepositoryCreator(); -
好吧,如果我有这些循环错误,我有点想我的设计模式一定是错误的;)虽然使用
Lazy<IUserRepository>有一个简单的解决方案,但感谢您的建议