How do I register a generic type in MVVMCross

c#, generics, mvvmcross

Solution

The default IoC container in MvvmCross is https://github.com/MvvmCross/MvvmCross/blob/v3.1/CrossCore/Cirrious.CrossCore/IoC/MvxSimpleIoCContainer.cs

It maintains a dictionary of service types (interfaces) to `resolvers` (objects which implement `IResolver`)

The `IResolver`'s currently supported only knows about how to supply actual types - not generic families of types. So this default IoC container and its resolvers cannot currently serve multiple instances in the way you request.

If you wanted to, you could extend or replace MvvmCross's default IoC Container with one that knows about families of types - the interface you'd need to support is https://github.com/MvvmCross/MvvmCross/blob/v3.1/CrossCore/Cirrious.CrossCore/IoC/IMvxIoCProvider.cs and the https://github.com/MvvmCross/MvvmCross/blob/v3.1/CrossCore/Cirrious.CrossCore/IoC/MvxSimpleIoCContainer.cs might be useful for you as a base class.

Alternatively, you could continue to use the `MvxSimpleIoCContainer` service and could register a non-generic service to supply your types at runtime - e.g. something with an interface:

public interface ISerializationStrategyFactory 
{
     ISerializationStrategy<T> CreateFactory<T>();
}

From the code in your question, I think this could be implemented just by:

public class SerializationStrategyFactory : ISerializationStrategyFactory 
{
     public ISerializationStrategy<T> CreateFactory<T>()
     {
         return new SerializationStrategy<T>();
     }
}

As one final alternative you could also use some reflection and a `foreach` loop to determine which classes to use in your current multiple calls to: `Mvx.RegisterType<ISerializationStrategy<IdentityProvider>,SerializationStrategy<IdentityProvider>>();`

Problem

I have an interface defined as follows: ``` public interface ISerializationStrategy<T> ``` and also a generic implementation: ``` public class SerializationStrategy<T> : Core.Strategies.ISerializationStrategy<T> ``` When I register this in the IOC do I have to do the following for each type: ``` Mvx.RegisterType<ISerializationStrategy<IdentityProvider>,SerializationStrategy<IdentityProvider>>(); ... each type ``` Or is there a way to register an open generic (I think thats what it's called). The following doesn't work: ``` Mvx.RegisterSingleton(typeof (ISerializationStrategy<>),typeof (SerializationStrategy<>)); ``` Thanks Ross

Original source