IDb依赖解析器是否仅适用于无参数构造函数

本文关键字:适用于 参数 构造函数 是否 依赖 IDb | 更新日期: 2023-09-27 18:35:34

我一直在尝试使用此示例将服务注入我的 IDbInterceptor 中。解析拦截器及其依赖项 (ITenantContext) 工作正常,只要我不向 DbConfiguration 注册 AutofacDbDependencyResolver。

但是当我这样做时,我收到错误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);

这是我的 IDb依赖关系解析器:

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>();
    }
}

IDb依赖解析器是否仅适用于无参数构造函数

检查 WebJobsTenantContext 具体类上的参数类型。

如果类型本身已注册到 DI 引擎,则只有这样才会发生链接解析。

如果它们是非 DI 注册的参数类型(基元类型等),则需要让 DI 引擎知道其值。

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

此错误意味着由 IDbDependencyResolver 解析的服务之一依赖于 DbContext。