我试图使用动态DI。我有我的配置:
container.RegisterType<IUserAdditionalData, UserAdditionalDataRepository>(
new HierarchicalLifetimeManager());
container.RegisterType<IPermission, PermissionRepository>(
new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver.UnityResolver(container);
此时,一切都好。但我需要动态设置我的类。我有两个类,PermissionRepository和PermissionRepositoryTwo,它们是从IPermission实现的,所以我想在PermissionRepository和PermissionRepositoryTwo之间切换。我读过我可以使用策略模式,有人知道如何解决这个问题?
答案 0 :(得分:3)
这种常见模式是代理模式。此模式允许您延迟决定使用哪个实现直到运行时并在代理中隐藏决策,同时仍允许在前面构建完整的对象图。
示例:
public sealed class RequestPermissionSelectorProxy : IPermission
{
private readonly PermissionRepository one;
private readonly PermissionRepositoryTwo two;
public RequestPermissionSelectorProxy(
PermissionRepository one, PermissionRepositoryTwo two) {
this.one = one;
this.two = two;
}
// Here select the permission based on some runtime condition. Example:
private IPermission Permission =>
HttpContext.Current.Items["two"] == true ? two : one;
public object PermissionMethod(object arguments) {
return this.Permission.PermissionMethod(arguments);
}
}
以下是如何注册:
container.RegisterType<IPermission, RequestPermissionSelectorProxy>(
new HierarchicalLifetimeManager());