[FIXED] How to resolve service with AutoFac from type of a variable

Issue

I have a class with method

public Task ServiceResolver(ILifetimeScope scope, IViewModel viewModel)
{
 Type type = viewModel.GetType();
 scope.Resolve<type>();
}

Is it possible to resolve the service similar to that using GetType or typeof(), this doesn’t work but I think if there is other option.

Or maybe there is another better way to resolve services outside the class. The problem is I have multiple viewModels and if I want to use inside viewModel other Resolved viewModel inside I have to refer to AutoFac container or resolve all of them before start of the app.

Solution

You should be able to pass the type directly to Resolve:

public Task ServiceResolver(ILifetimeScope scope, IViewModel viewModel)
{
 Type type = viewModel.GetType();
 var resolvedInstance = (IViewModel)scope.Resolve(type);
}

That overload of Resolve returns object, so you will want to cast it before you use it.

Answered By – Alistair Evans

Answer Checked By – Willingham (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published