我一直在嘗試使用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>();
}
}