在尝试解析我的服务类时,我遇到了一个错误,即无法构造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);
MyDbContext
和MRepository
相关的 DI 配置代码。 - NightOwl888