Search code examples
c#xamarin.formsunity-containerprismioc-container

Register an instance of a service in Prism.Unity which relies on another service


I have an authentification service, that I register in my Unity Container like so:

Container.RegisterInstance<IAuthenticationService>(new AuthenticationService());

My problem is that my AuthentificationService relies on INavigationService, and its constructor takes this as an argument:

public AuthenticationService(INavigationService navigationService)

From my understanding, the Unity Container is responsible for injecting the INavigationService implementation. But in this case, I am providing the AuthenticationService instance, so how can I tell Unity to inject the INavigationService in my AuthentificationService implementation?


Solution

  • In the first place, you use a DI Container like unity to get rid of new. So registering an instance is kind of a last resort, if you're forced to do it.

    Normally, you want to register types, telling unity what to create, leaving the how to the container.

    You should write

    Container.RegisterType<IAuthenticationService, AuthenticationService>( new ContainerControlledLifetimeManager() );
    

    When it comes to creating the AuthenticationService instance, unity will try to resolve all constructor parameters, and pass the INavigationService to your AuthenticationService:

    internal class AuthenticationService
    {
        public AuthenticationService( INavigationService navigationService )
        {
            // here you've got the Navigation Service...
        }
    }