我在基本級別上使用autofac來處理依賴注入。我此刻的配置很簡單:在WebAPI perRequest中按需使用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的函數功能的支持:所以在你的'公共TestRepository(Func鍵 userRepositoryCreator)'和你的'測試()'方法只寫:'var scopeUserRepo = userRepositoryCreator();' –
nemesv
2014-10-27 13:01:17
以及我有點想象我的設計模式必須是錯誤的,如果我有那些循環錯誤;)雖然有一個簡單的解決方案使用Lazy但感謝您的建議 –
2014-10-27 13:06:00