gpt4 book ai didi

c# - 使用 Windsor 的通用存储库生命周期配置

转载 作者:行者123 更新时间:2023-11-30 22:39:26 25 4
gpt4 key购买 nike

我不知道如何配置正确的 Windsor 容器以与 Windows 应用程序中的存储库一起使用。我有通用存储库实现存储库,其中 T 是实体类型,它有一个依赖项 IDatacontextProvider,它为其提供数据上下文:

public class Repository<T> : IRepository<T> where T : class
{
protected DataContext DataContext;
public Repository(IDataContextProvider dataContextProvider) {
DataContext = dataContextProvider.DataContext;
}
....
}

对于简单的事情,使用以下配置一切正常:

 container.Register(                                
Component.For<IDataContextProvider>()
.ImplementedBy<DataContextProvider>()
.Lifestyle.Transient,
Component.For(typeof(IRepository<>))
.ImplementedBy(typeof(Repository<>))
.Lifestyle.Transient, ....

当我尝试加入来自多个存储库的不同实体时,只要每个存储库实例具有不同的数据上下文实例,就会出现问题。
例如我有简单的服务:

public class SimpleService : ISimpleService {
public SimpleService(IRepository<Order>, IRepository<OrderLine>) {
....
}
}

我可以将 IDataContextProvider 设为 Singleton,但我认为这会带来更大的问题。
我可以将 IDataContextProvider 传递给 SimpleService,并尝试在那里解析存储库实例,但这需要额外的代码才能使服务易于测试,并且需要额外的依赖项。可能有人知道如何解决这个问题?

更新:按照建议,我创建了存储库工厂(它与答案中提出的略有不同,它不直接依赖于数据上下文,但想法非常相同):

 public interface IRepositoryFactory
{
IRepository<T> GetRepository<T>() where T:class;
}

public class RepositoryFactory : IRepositoryFactory
{
private readonly IDataContextProvider dataContextProvider;

public RepositoryFactory(IDataContextProvider dataContextProvider)
{
this.dataContextProvider = dataContextProvider;
}

public IRepository<T> GetRepository<T>() where T : class
{
return new Repository<T>(dataContextProvider);
}
}

最佳答案

如果中间有另一层,比如 RepositoryFactory 呢?那个人可能有一种短暂的生活方式。从工厂创建的所有存储库将共享相同的 DataContext 实例。您还需要更改您的存储库类,以便它们采用 DataContext 实例而不是 DataContextProvider。

public class RepositoryFactory : IRepositoryFactory
{
protected DataContext dataContext;
public RepositoryFactory(IDataContextProvider provider)
{
dataContext = dataContextProvider.DataContext;
}

public IRepository<T> GetRepository<T>()
{
return new Repository<T>(dataContext);
}
}

public class SimpleService : ISimpleService {
public SimpleService(IRepositoryFactory factory) {
....
}
}

关于c# - 使用 Windsor 的通用存储库生命周期配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5726601/

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