Search code examples
dryioc

Override certain implementation when resolving a dependency


I have read to documentation and can't find anything about resolving a type and at the same time override some of its dependencies. Easiest to illustrate with an example

public class A
{
    public A(IServiceA a, IServiceB b) {}    
}
// Resolve scenarion
type => 
{
    // type is A
    var a = Container.Resolve<IServiceA>();
    a.SomeProperty = "magic";
    return Container.Resolve(type) // TODO: How to resolve A using a
}

Does it make sense? Was looking for something like

return Container.Resolve(type, Rule.Override.TypeOf<IServiceA>(a));

Great job with DryIoc

Edit (2016-05-26) My question was missleading. Below is complete code example (for prism)

ViewModelLocationProvider.SetDefaultViewModelFactory((view, type) =>
{
     var page = view as Page;
     if (page != null)
     {                    
          var navigationService = Container.Resolve<INavigationService>();
          ((IPageAware)navigationService).Page = page;
          var @override = Container.Resolve<Func<INavigationService, type>>(); // How to do this
          return @override(navigationService);
     }
     return Container.Resolve(type);
});

Solution

  • Resolve as Func with parameter you want to pass:

    var factory = Container.Resolve<Func<IServiceA, A>>();
    var result = factory(a);
    

    Update:

    Given the runtime Type to resolve:

    type => 
    {
        // type is A
        var a = Container.Resolve<IServiceA>();
        a.SomeProperty = "magic";
    
        // Asking for required service type, but wrapped in Func returning object
        var factory = Container.Resolve<Func<IServiceA, object>>(requiredServiceType: type);
        return factory(a);
    }