我得到了以下服务:
IRepository<TEntity, TPrimaryKey>
..为此我创建了一个定义为:
Repository<TEntity, TPrimaryKey>.
如何在 autofac 中注册它以便我可以将其解析为:
IRepository<User, int>
我得到了以下服务:
IRepository<TEntity, TPrimaryKey>
..为此我创建了一个定义为:
Repository<TEntity, TPrimaryKey>.
如何在 autofac 中注册它以便我可以将其解析为:
IRepository<User, int>
builder.RegisterGeneric(typeof (Repository<,>)).As(typeof (IRepository<,>));
我喜欢autofac。
作为您自己的解决方案的替代方案,您可以尝试定义一个工厂来创建新的存储库实例:
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 容器返回的实例通常具有较长的生命周期。
另一个提示:您可能想要重构主键类型的使用。总是要求存储库<User, int>
而不是存储库会很麻烦<User>
。也许您找到了一种方法来抽象出工厂内部的主键。
我希望这有帮助。