使用Unity时的Entity Framework错误

3

在尝试解析我的服务类时,我遇到了一个错误,即无法构造DbContext,因为它是一个抽象类。错误信息如下:

Unity.Exceptions.ResolutionFailedException: 'Resolution of the dependency failed, type = 'MyService.MyClass', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was: 
  Resolving ...
      ...
          Resolving MyApp.MyRepository,(none)
          Resolving parameter 'myDbContext' of constructor MyApp.MRepository(MyApp.IMyDbContext myDbContext)
          ...
              Resolving parameter 'existingConnection' of constructor MyApp.MyDbContext(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, System.Boolean contextOwnsConnection)
                Resolving System.Data.Common.DbConnection,(none)
'

DBContext 的结构如下:

public class MyDbContext : System.Data.Entity.DbContext, IMyDbContext
{
    public MyDbContext()
        : base("MainConnectionString")
    {
    }

我的猜测是EF在配置文件中查找连接字符串;但是连接字符串已经被定义了:
<connectionStrings>
    <add name="MainConnectionString" connectionString="Server=.\SQLEXPRESS;Database=MyDB;User Id= . . ." providerName="System.Data.SqlClient" />
</connectionStrings>

Unity注册:

因此,我的问题是EF是如何确定构建该类的,因为很明显我在配置中缺少某些内容。

UnityContainer container = new UnityContainer();
container.RegisterType<IMyDbContext, MyDbContext>();
container.RegisterType<IMyRepository, MyRepository>();
container.RegisterInstance<IUnityContainer>(container);

2
请查看:https://dev59.com/3WvXa4cB1Zd3GeqPMsYm - Ramesh Rajendran
我已经查看了那个问题,但我不明白其相关性。我正在注册DbContext类型。 - Paul Michaels
在这种情况下是否可以进行依赖注入(DI)呢? "MyDbContext : System.Data.Entity.DbContext, IMyDbContext" - Shiwanka Chathuranga
请发布与 MyDbContextMRepository 相关的 DI 配置代码。 - NightOwl888
你是对的...但也有错。我没有必要将UnityContainer注册到自身。然而,如果不传递构造函数参数(正如我在答案中所述),我会得到相同的错误。 - Paul Michaels
显示剩余2条评论
2个回答

0

我通过将注册更改为显式传递连接字符串名称来使其工作:

UnityContainer container = new UnityContainer();
container.RegisterType<IMyDbContext, MyDbContext>(new InjectionConstructor("MainConnectionString"));
. . .
container.RegisterInstance<IUnityContainer>(container);

0
根据this answer
Unity将解析具体类型(.Resolve),但必须通过将它们与具体类型相关联来显式注册接口。
所以,你有两个选择:
1.使用Unity注册IMyDbContext接口
2.停止使用IMyDbContext并使用具体类型(在这种情况下,Unity将自动解析它,尽管您可能需要手动控制生命周期)
请注意,使用DI的主要目的是能够交换实现,因此,如果您的应用程序实际上没有为另一个相同的数据库架构交换,则在这种情况下可能不需要接口。

但是,查看调用堆栈,它甚至没有尝试解析IDbContext,而是IMyDbContext - 这是已注册的。 - Paul Michaels
糟糕,那是一个打字错误。 - NightOwl888
我正在注册IMyDbContext。从错误信息来看,它似乎在尝试实例化MyDbContext时抱怨DbConnerction - 因此错误不是找不到IoC引用,而是无法实例化它。 - Paul Michaels

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接