Search code examples
c#xamarindependency-injectionxamarin.formsunity-container

Unity.Resolve for a class with a dependency injection


I am using Unity to control Dependency Injection in my Xamarin Forms application. I have a view model class that takes a parent id and a unity injected service as constructor parameters.

public class BrowseViewModel {
    public BrowseViewModel(int parentId, IInjectedService injectedService) {
    }
}

I have registered the class in the unity container.

unityContainer.registerType<BrowseViewModel>();

I have also registered the service in the unity container.

unityContainer.registerType<IInjectedService, InjectedService>();

My question is, how do I specify the value for parentId when Unity creates an instance of my class? I don't think I should have to specify the injectedService parameter because I have already registered this class with unity and it is a singleton class.


Solution

  • You need to register BrowseViewModel like that:

    container.RegisterType<Func<int, BrowseViewModel>>(
                    new InjectionFactory(c =>
                        new Func<int, BrowseViewModel>(id=> c.Resolve<BrowseViewModel>(new ParameterOverrides { { "parentId", id},))));
    

    Then in contrutor where you use BrowseViewModel, you need to use Func<int, BrowseViewModel> browseViewMdoelFactory and use it like that:

    class SomeViewClass
    {
        SomeViewClass(Func<int, BrowseViewModel> browseViewMdoelFactory)
        {    
        browsceViewModelFactory(parentId);
        }
    }