【发布时间】:2018-01-30 21:30:17
【问题描述】:
在尝试解析我的服务类时,我收到一个错误,指出无法构造 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);
【问题讨论】:
-
我看过那个问题,但我不明白相关性。我正在注册 DbContext 类型。
-
在这种情况下可以进行 DI 吗? "MyDbContext : System.Data.Entity.DbContext, IMyDbContext"
-
是 - 许多 EF 应用程序使用 DI
-
请贴出
MyDbContext和MRepository的相关DI配置代码。
标签: c# entity-framework dependency-injection entity-framework-6 unity-container