我在基本级别使用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.
答案 0 :(得分:1)
您不能只在Web API中开始生命周期范围。请求生命周期范围随请求消息一起提供。通过手动创建这样的请求生命周期范围,如果您具有每个请求的生命周期范围依赖性,那么您将无法获得所需的结果 - 尤其是,因为您创建的范围将是与实际请求生存期不同。你不会得到你应该得到的终身分享。
There is a detailed FAQ about troubleshooting per-request lifetime scope issues应该可以帮助您顺利前进。您可能也对the documentation on properly handling circular dependencies in Autofac感兴趣。
答案 1 :(得分:1)
您可以在构造函数中使用ILifetimeScope:
public class TestRepository : ITestRepository
{
private ILifetimeScope _scope;
public TestRepository(ILifetimeScope scope)
{
_scope = scope;
}
public void Test()
{
var scopeUserRepo = _scope.Resolve<IUserRepository>();
}
}