2

I'm trying to use dynamic DI. I have my configuration:

container.RegisterType<IUserAdditionalData, UserAdditionalDataRepository>(
    new HierarchicalLifetimeManager());
container.RegisterType<IPermission, PermissionRepository>(
    new HierarchicalLifetimeManager());         

config.DependencyResolver = new UnityResolver.UnityResolver(container);

At this point, It's all Ok. But I need to set my class dynamically. I have two class, PermissionRepository and PermissionRepositoryTwo, that implements from IPermission, so I'd like to switch between PermissionRepository and PermissionRepositoryTwo. I've read I can use strategy pattern, someone have any idea how can resolve this?

2
  • 2
    How do you wish to switch between the two implementations? Based on a configuration switch in the web.config? Based on some runtime data like a user request? Commented Aug 9, 2016 at 15:37
  • Thanks for your reply. I will use a setting into request. I thought I could configure into WebApiConfig file, but this file is only called once. Commented Aug 9, 2016 at 16:09

1 Answer 1

3

The common pattern for this is the proxy pattern. This pattern allows you to delay the decision about which implementation to use until runtime and hides the decision within the proxy, while still allowing the complete object graph to be built up front.

Example:

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);
    }
}

Here's how to register:

container.RegisterType<IPermission, RequestPermissionSelectorProxy>(
    new HierarchicalLifetimeManager());  
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Your answer help me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.