作为您自己的解决方案的替代方案,您可以尝试定义一个工厂来创建新的存储库实例:
public interface IRepositoryFactory
{
IRepository<TEntity, TPrimaryKey>
CreateRepository<TEntity, TPrimaryKey>();
// Perhaps other overloads here
}
internal class RepositoryFactory : IRepositoryFactory
{
public IContainer Container { get; set; }
public IRepository<TEntity, TPrimaryKey>
CreateRepository<TEntity, TPrimaryKey>()
{
return container.Resolve<Repository<TEntity, TPrimaryKey>>();
}
}
您可以按如下方式注册RepositoryFactory:
builder.Register(c => new RepositoryFactory() { Container = c })
.As<IRepositoryFactory>()
.SingleInstance();
现在您可以将IRepositoryFactory 声明为构造函数参数并创建新实例。看看这个使用依赖注入的ProcessUserAccountUpgradeCommand 类的例子:
public ProcessUserAccountUpgradeCommand : ServiceCommand
{
private readonly IRepositoryFactory factory;
ProcessUserAccountUpgradeCommand(IRepositoryFactory factory)
{
this.factory = factory;
}
protected override void ExecuteInternal()
{
// Just call the factory to get a repository.
var repository = this.factory.CreateRepository<User, int>();
User user = repository.GetByKey(5);
}
}
虽然使用工厂而不是直接获取存储库可能看起来有点麻烦,但您的设计将清楚地传达检索到新实例的信息(因为您调用了CreateRepository 方法)。从 IoC 容器返回的实例通常是 expected to have a long life。
另一个提示:您可能想要重构主键类型的使用。总是要求<User, int> 的存储库而不仅仅是<User> 存储库会很麻烦。也许你找到了一种方法来抽象出工厂内部的主键。
我希望这会有所帮助。