0

我一直在嘗試使用this示例將服務注入到IDbInterceptor中。只要我沒有使用DbConfiguration註冊AutofacDbDependencyResolver,解析攔截器及其依賴關係(ITenantContext)就可以正常工作。IDbDependencyResolver僅適用於無參數構造函數嗎?

但是,當我這樣做時,我得到錯誤An exception was thrown while invoking the constructor 'Void .ctor()' on type 'DMDbContext'. ---> ValueFactory attempted to access the Value property of this instance.。如果我將ITenantContext更改爲使用無參數的構造函數,但卻無法達到DI的全部目的,則不會出現該錯誤。

這是我的IoC容器:

var builder = new ContainerBuilder(); 
builder.RegisterType<TenantIdDMDbCommandInterceptor>().As<IDbInterceptor>(); 
builder.RegisterType<DMDbContext>().AsSelf().InstancePerLifetimeScope(); 

builder.RegisterType<WebJobsTenantContext>().As<ITenantContext().InstancePerLifetimeScope(); 

builder.RegisterInstance(config); 

// Need to register webjob class in Autofac as well 
builder.RegisterType<Functions>().InstancePerDependency(); 

var container = builder.Build(); 

//This line causes the exception 
DbConfiguration.Loaded += (s, e) => 
    e.AddDependencyResolver(new AutofacDbDependencyResolver(container), overrideConfigFile: false); 

這是我IDbDependency解析:

public class AutofacDbDependencyResolver : IDbDependencyResolver 
{ 
    private ILifetimeScope container; 

    public AutofacDbDependencyResolver(ILifetimeScope container) 
    { 
     this.container = container; 
    } 

    public object GetService(Type type, object key) 
    { 
     if (container.IsRegistered(type)) 
     { 
      return container.Resolve(type); //TODO: Why does this only work with parameterless contructors? 
     } 

     return null; 
    } 

    public IEnumerable<object> GetServices(Type type, object key) 
    { 
     if (container.IsRegistered(type)) 
     { 
      return new object[] { container.Resolve(type) }; 
     } 

     return Enumerable.Empty<object>(); 
    } 
} 

回答

0

這個錯誤意味着你的一個由IDbDependencyResolver解決的服務依賴於DbContext。

1

檢查的WebJobsTenantContext具體類的參數類型。

如果類型本身是在DI引擎中註冊的,那麼只有鏈式解析會發生。

如果它們是非DI註冊的參數類型(原始類型等),那麼您需要讓DI引擎知道它的值。

builder.RegisterType<WebJobsTenantContext>() 
.WithParameter("param1", someValue) 
.As<ITenantContext().InstancePerLifetimeScope();