0

I try to get Unity to resolve a type (object) using a factory method with parameter, but i can't get this working. The source of the Problem is described in this answer answer.

It says i need to register every view with:

m_Container.RegisterType<Object, View>("View");

Otherwise the RequestNavigate("View") Method will fail, but i don't like this approach. I wan't to navigate with RequestNavigate("Namespace.View") but this does not work.

So i tried to tell the Unity Container how to resolve the views:

this.Container.RegisterType<object>(new InjectionFactory(this.ViewObjectFactory));

private object ViewObjectFactory(IUnityContainer iUnityContainer, Type type, string name)
{
    //Never called
}

But if the Container gets called with the following parameters:

this.Container.Resolve(typeof(object), "Namespace.View");

A object gets created and the factory method is ignored, how can i get unity to call a factory method for a type (even if the resolve method is called with a name).

Community
  • 1
  • 1
quadroid
  • 8,444
  • 6
  • 49
  • 82

1 Answers1

1

When prism is resolving the view it's using the named registration. You have the injection factory method on the non-named registration. I don't believe there is a way to tell unity to resolved the non-named registration when resolving a named one. You could chain them down to a common one but that doesn't help you as you would still need to name them all. If you really just want to use the namespace you can just register the fullname as the name.

I would make an extension method to handle it for me

public static IUnityContainer RegisterView<TView>(this IUnityContainer container)
{
    return container.RegisterType<object, TView>(typeof (TView).FullName);
}

You would use it as

m_Container.RegisterView<View>();

Then for prism you would need to change the request for navigation to always pass in the view's fullname. Again I would make an extension method for those

public static void RequestNavigate<TView>(this IRegion region)
{
    region.RequestNavigate(new Uri(typeof (TView).FullName, UriKind.Relative));
}

public static void RequestNavigate<TView>(this IRegionManager region, string regionName)
{
    region.RequestNavigate(regionName, new Uri(typeof (TView).FullName, UriKind.Relative));
}

In code you would use it like

region.RequestNavigate<View>();

or

regionManager.RequestNavigate<View>("Main");

There are 6 other overloads for RequestNavigate that you would need to create extension methods for as well if you used them and wanted to use it this way.

CharlesNRice
  • 3,219
  • 1
  • 16
  • 25