一種方法是讓RepositoryFactory實現IRepositoryFactory,然後註冊。解析類型可以獲得工廠,然後調用其CreateAuthoringRepository方法。如果需要,您可以創建一個名爲CreateAuthoringRepositoryForCurrentIdentity的重載,或者使用Unity註冊工廠的IIdentity依賴關係。
我可能只是注入一個工廠,並保留CreateAuthoringRepository方法,然後讓客戶端通過WindowsIdentity.GetCurrent()。這樣身份總是新鮮的,你可以嘲笑工廠進行測試。
或者,你可以用InjectionFactory指定一個委託:
void Main()
{
using (var container = new UnityContainer())
{
container.RegisterType<IAuthoringRepository>(
new InjectionFactory(c => CreateAuthoringRepository()));
Console.WriteLine("debug - resolving model");
var model = container.Resolve<Model>();
}
}
public IAuthoringRepository CreateAuthoringRepository()
{
Console.WriteLine("debug - calling factory");
return new AuthoringRepository
{ Identity = WindowsIdentity.GetCurrent() };
}
public class Model
{
public Model(IAuthoringRepository repository)
{
Console.WriteLine(
"Constructing model with repository identity of "
+ repository.Identity);
}
}
public interface IAuthoringRepository
{
IIdentity Identity { get; }
}
public class AuthoringRepository : IAuthoringRepository
{
public IIdentity Identity { get; set; }
}
此打印:
debug - resolving model
debug - calling factory
Constructing model with repository identity of System.Security.Principal.WindowsIdentity
這對統一2.0。使用較早的版本,請參閱StaticFactoryExtension。
謝謝!像魅力一樣工作=) – burnt1ce
完美!這也適用於我。 –