Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity - ResolveAll by name with condition

I was wondering if it is possible to resolve all dependancies in Unity by some condition on the name that they were registered.

For example: Resloving all interfaces registered where the name registered starts with "ProcessA".

And if there is no way to do this then perhaps how can i extend Unity to allow this.

like image 823
JarJarrr Avatar asked Sep 07 '26 05:09

JarJarrr


1 Answers

You should be able to use Registrations to do this and I would recommend an extension method rather than extending Unity directly:

var matches = c.Resolve<IMyService>(name => name.StartsWith("ProcessA"));

Using this extension method:

public static class MyUnityExtensions
{
    public static IEnumerable<T> Resolve<T>(this IUnityContainer c, Func<string, bool> match)
    {
        var matches = c.Registrations.Where(r => match(r.Name));

        foreach (var registration in matches)
        {
            yield return c.Resolve<T>(registration.Name);
        }
    }

}
like image 155
Mike Valenty Avatar answered Sep 09 '26 19:09

Mike Valenty