简体   繁体   中英

How to resolve the dependencies in Prism + DryIoC

I am using Prism.DryIoc.Forms (7.1.0.431) in one of my Xamarin.Forms (4.0.0.497661) projects. I am facing issue while resolving the dependency in other service classes.

Use case:

We have a service called RestService which takes care of network calls and we have implemented one more service called ProfileService in which we get the user information and other stuff related to Profile's service. I am thinking to resolve the RestService dependency in ProfileService to make the network calls.

I have registered both the services in App.xaml.cs under RegisterTypes() method.

If you want to access the underlying container used by Prism.Forms. In your case DryIoc, you can easily get inside RegisterTypes method.

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
   containerRegistry.RegisterForNavigation<NavigationPage>();
   AppContainer = containerRegistry.GetContainer(); //Assigning actual dryioc container
}

AppContainer is an property declared in App.xaml.cs class like below.

Note:- GetContainer method is an extension method which is available in Prism.DryIoc namespace. Import namespace

using Prism.DryIoc;

//Private and Public variables
public partial class App
{
    /// <summary>
    /// Actual Dry Ioc Container which can be called and used for manual registering and resolving dependencies.
    /// </summary>
    public static IContainer AppContainer { get; set; }
}

Now you can use DryIoc container like below.

var authService = App.AppContainer.Resolve<IAuthenticationService>();//you need to register IAuthenticationService inside RegisterType Method.

Note:- import DryIoc namespace in your class where you are calling above line of code.

using DryIoc;

Happy Coding :)

Note:- The above approach is not recommended as this will make your class / code untestable.

I am thinking to resolve the RestService dependency in ProfileService to make the network calls.

Never ever actively resolve anything anywhere, except once at the root of the application. (*)

What you want to do is to inject the dependency, ie you create a constructor parameter:

internal class ProfileService : IProfileService
{
    public ProfileService( IRestService restService )
    {
        // store restService for later, use it now... but have it injected, don't resolve it!
    }
}

(*) convention-over-registration stuff like the ViewModelLocator is a notable exception, but in fact, conceptionally, we inject a universal factory there more than resolving individual view models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM