IDbDependencyResolver仅适用于无参数构造函数吗?
问题描述:
我一直在尝试使用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>();
}
}
答
这个错误意味着你的一个由IDbDependencyResolver解决的服务依赖于DbContext。
答
检查的WebJobsTenantContext具体类的参数类型。
如果类型本身是在DI引擎中注册的,那么只有链式解析会发生。
如果它们是非DI注册的参数类型(原始类型等),那么您需要让DI引擎知道它的值。
builder.RegisterType<WebJobsTenantContext>()
.WithParameter("param1", someValue)
.As<ITenantContext().InstancePerLifetimeScope();