IDbDependencyResolver仅适用于无参数构造函数吗?

时间:2016-02-19 21:58:56

标签: c# entity-framework dependency-injection entity-framework-6 autofac

我一直试图使用this示例将服务注入我的IDbInterceptor。只要我没有使用DbConfiguration注册AutofacDbDependencyResolver,解析具有依赖关系的拦截器(ITenantContext)就可以正常工作。

然而,当我这样做时,我收到错误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>();
    }
}

2 个答案:

答案 0 :(得分:1)

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

如果类型本身已在DI引擎中注册,则只会发生链式分辨率。

如果它们是非DI注册参数类型(原始类型等),那么你需要让DI引擎知道它的值。

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

答案 1 :(得分:0)

此错误意味着IDbDependencyResolver解析的某个服务依赖于DbContext。