Autofac 无法解析 DbContext

5 c# autofac

我从 Autofac 收到此错误消息;:

在类型 'MyService`1[MyContext]' 上找到的带有 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' 的构造函数都不能用可用的服务和参数调用:无法解析构造函数 'Void .ctor 的参数 'MyContext context' (MyContext)'。

错误发生在这行代码上(也显示在下面的代码中):

IMyService myService = container.Resolve<IMyService>();  // error here
Run Code Online (Sandbox Code Playgroud)

我有兴趣注意到,当我在我的注册中包含这一行时,一切正常:

builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
Run Code Online (Sandbox Code Playgroud)

当我注册 AnyConcreteType 时,这一切都有效...这一事实让我相信我没有注册某些东西。我的问题是我没有注册什么?错误消息似乎将 MyContext 命名为罪魁祸首,但显然我正在按如下所示进行注册。
我真的不想使用 AnyConcreteType ......因为我只想明确注册我需要的类。

我的服务是这样构建的:

public class MyService<T> : BaseService<T>, IMyService where T:DbContext,IMyContext
{
    public MyService(T context) : base(context)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

MyService 派生自 BaseService:

public abstract class BaseService<T> : IDisposable where T:DbContext, IMyContext
{
    internal T db;

    public BaseService(T context)
    {
        db = context;
    }
}
Run Code Online (Sandbox Code Playgroud)

MyContext 传递给 MyService 并构造如下:

public partial class MyContext : DbContext, IMyContext
{
    public MyContext(INamedConnectionString conn)
        : base(conn.ConnectionString)
    {
        Configuration.ProxyCreationEnabled = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是 NamedConnectionString

public class NamedConnectionString : INamedConnectionString
{
    public string ConnectionString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

以下是我注册上述内容的方法:

builder.RegisterType<MyService<MyContext>>().As<IMyService>();  
builder.RegisterType<NamedConnectionString>().As<INamedConnectionString>().SingleInstance();
builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope();
builder.RegisterType<DbContext>(); // is this necessary??
Run Code Online (Sandbox Code Playgroud)

我是这样称呼它的:

    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    INamedConnectionString namedConnectionString = container.Resolve<INamedConnectionString>();
    namedConnectionString.ConnectionString = myConnectionString;
    IMyService myService = container.Resolve<IMyService>();  // error here
Run Code Online (Sandbox Code Playgroud)

小智 7

Autofac 和 ASP .Net MVC 4 Web API

上面的线程是相关的。它没有回答问题,但它帮助我开始朝着正确的方向进行故障排除。解决方案在这里:

我删除了这两行:

builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope();
builder.RegisterType<DbContext>(); // is this necessary??
Run Code Online (Sandbox Code Playgroud)

并用这个替换它们:

builder.RegisterType<MyContext>().InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)