gpt4 book ai didi

frameworks - 使用 Entity Framework 和 CaSTLe Windsor 容器解决通用存储库的问题

转载 作者:行者123 更新时间:2023-12-02 05:13:41 27 4
gpt4 key购买 nike

我正在使用 Entity Framework 实现通用存储库v4,并且存储库必须由 Windsor container 解析.

首先是界面,

public interface IRepository<T>
{
void Add(T entity);
void Delete(T entity);
T Find(int key)
}

然后具体类实现接口(interface)

public class Repository<T> : IRepository<T> where T: class
{
private IObjectSet<T> _objectSet;
}

所以我需要 _objectSet 来做上一节课中类似的事情,

    public void Add(T entity)
{
_objectSet.AddObject(entity);
}

现在的问题是,如您所见,我正在使用像 IObjectSet 这样的 Entity Framework 接口(interface)来完成这项工作,但是这种类型需要 T 泛型类型的约束“其中 T:类”。

当 Windsor 尝试解析其具体类型时,该约束会导致异常。温莎配置如下所示。

<castle>
<components>
<component id="LVRepository"
service="Repository.Infraestructure.IRepository`1, Repository"
type="Repository.Infraestructure.Repository`1, Repository"
lifestyle="transient">
</component>
</components>
</castle>

容器解析代码:

IRepository<Product> productsRep =_container.Resolve<IRepository<Product>>();

现在我得到的异常:

System.ArgumentException: GenericArguments[0], 'T', on 'Repository.Infraestructure.Repository`1[T]' violates the constraint of type 'T'. ---> System.TypeLoadException: GenericArguments[0], 'T', on 'Repository.Infraestructure.Repository`1[T]' violates the constraint of type parameter 'T'.

如果我删除具体类中的约束和对 IObjectSet 的依赖(如果我不这样做,我会收到编译错误)一切正常,所以我认为这不是容器问题,但是IObjectSet 在实现中是必须的。

我该如何解决这个问题?

最佳答案

那是很久以前的事了,但一种解决方法是在您的界面上施加相同的约束。

public interface IRepository<T> where T : class

关于frameworks - 使用 Entity Framework 和 CaSTLe Windsor 容器解决通用存储库的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3057865/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com