Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically register generic classes with a name with Unity?

I have an assembly with a lot of classes (300+) with a BaseClass and I want register a generic class with a interface.

With unity you have to register by {Name} if you want to resolve an array of objects of the interface. I want an array of objects in the MainViewModel automatically.

Is there a way to automate this with reflection? Any suggestions?

Example (pseudo):

public class BaseClass
{
   public void doFoo();
}

public ClassNumber001 : BaseClass
{
}
public ClassNumber002 : BaseClass
{
}

public interface ISuperman
{
}

public class Superman : ISuperman where T : BaseClass
{
}

public MainViewModel(IEnumerable<ISuperman> lotsofSuperman)
{
}

Working example by hand:

container.RegisterType<ISuperman, Superman <ClassNumber001>>("ClassNumber001");
container.RegisterType<ISuperman, Superman <ClassNumber002>>("ClassNumber002");
container.RegisterType<IEnumerable<ISuperman>, ISuperman[]>();
like image 657
Tim Avatar asked Oct 31 '22 23:10

Tim


1 Answers

This is something that comes to my mind that might work for you...

You can register the type as follows, and should work for the open generic.

container.RegisterType(typeof(ISuperman<>), typeof(Superman<>), ... );

Registering generic parameters and types

Hope this helps!

like image 149
gastonmancini Avatar answered Nov 09 '22 09:11

gastonmancini