使用Unity时实体框架错误

2024-02-05

在尝试解决我的服务类时,我收到一个错误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>

统一注册:

因此,我的问题是 EF 如何构建这个类,很明显我在配置中遗漏了一些东西。

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

As per 这个答案 https://stackoverflow.com/a/13752500:

Unity 将解析具体类型 (.Resolve),但必须通过将接口与具体类型关联来显式注册接口。

所以,你有 2 个选择:

  1. 注册IMyDbContext与Unity的接口
  2. 停止使用IMyDbContext并使用具体类型(在这种情况下,Unity 将自动解析它,尽管您可能需要手动执行以控制生命周期)

请注意,使用 DI 接口的主要目的是能够交换实现,所以如果您的应用程序实际上并未交换一个相同的数据库模式另一方面,在这种情况下您可能不需要该接口。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用Unity时实体框架错误 的相关文章