【发布时间】:2012-02-17 08:58:39
【问题描述】:
你好,
我在使用统一容器注册存储库时遇到问题。我有以下配置和类:
/* 通用存储库:*/
public class Repository<E> : IRepository<E> where E : EntityObject
{
private readonly ObjectContext _ctx;
public ObjectContext Context
{
get { return _ctx; }
}
public Repository(ObjectContext context)
{
_ctx = context;
}
}
/* 具体存储库:*/
public class SourceRepository : Repository<Source>
{
public SourceRepository(EntityContext context) : base(context) { }
}
/* EF 生成的上下文:*/
public partial class EntityContext : ObjectContext
{
public EntityContext() : base("name=EntityContext", "EntityContext")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
public EntityContext(string connectionString) : base(connectionString, "EntityContext")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
public EntityContext(EntityConnection connection) : base(connection, "EntityContext")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
}
/* 使用无参数构造函数注册EntityContext类型 */
<register type="ObjectContext" mapTo="EntityContext" name="EntityContext">
<constructor/>
</register>
/* 注册通用存储库(我不确定是否需要此注册)*/
<register type="IRepository[]" mapTo="Repository[]" name="Repository">
<lifetime type="transient" />
<constructor>
<param name="context">
<dependency name="EntityContext"/>
</param>
</constructor>
</register>
/* 注册具体存储库。我想注入EntityContext类型的构造函数依赖*/
<register type="IRepository[Source]" mapTo="SourceRepository" name="SourceRepository">
<lifetime type="transient" />
<constructor>
<param name="context">
<dependency name="EntityContext"/>
</param>
</constructor>
</register>
当我尝试加载配置时出现错误:
解析依赖失败,type = "BL.DataAccess.Repository.SourceRepository", name = "(none)"。 异常发生时:解决时。 例外情况是:InvalidOperationException - ObjectContext 类型有多个长度为 1 的构造函数。无法消除歧义。
我了解此异常的含义,但我不知道我的配置中哪里有错误。
你能帮忙吗?
谢谢。
【问题讨论】:
-
在构造函数配置中指定 EntityContext 作为参数类型可能会成功。
-
如果你的意思是:
所以它没有没有帮助。同样的错误。 -
看起来 SourceRepository 只有一个构造器。你能试试 Type t = typeof(SourceRepository); ConstructorInfo[] constructorInfos = t.GetConstructors();检查它有多少承包商。
-
是的,它只有一个构造函数
-
SourceRepository构造函数是否采用EntityContext,就像您的代码一样?还是真的需要ObjectContext?
标签: c# configuration repository unity-container