Skip to content

Instantly share code, notes, and snippets.

@royto
Created January 22, 2018 10:29
Show Gist options
  • Save royto/c108ed4cb60c38b57298df21d18e5ffe to your computer and use it in GitHub Desktop.
Save royto/c108ed4cb60c38b57298df21d18e5ffe to your computer and use it in GitHub Desktop.
Unity - DI - Inject Multiple interface implementations
namespace Demo.Service
{
public class DomainServiceService
{
public DomainServiceService(IDomainService[] domainServices)
{
foreach (var service in domainServices)
{
var name = service.GetName();
}
}
}
}
namespace Demo.InjectionTest
{
public interface IDomainService
{
string GetName();
}
public class OrderDomainService : IDomainService
{
public string GetName()
{
return "Order";
}
}
//Should be public to be available to AllClasses on register
public class CategoryDomainService : IDomainService
{
public string GetName()
{
return "Category";
}
}
}
using Microsoft.Practices.Unity;
using System.Linq;
namespace Demo
{
class Program
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
Container = new UnityContainer();
Container.RegisterTypes(
AllClasses.FromLoadedAssemblies().
Where(type => typeof(IDomainService).IsAssignableFrom(type)),
WithMappings.FromAllInterfaces,
WithName.TypeName,
WithLifetime.Transient);
// Via container resolve
var interfaces = UnityBootstrapper.Container.ResolveAll<IDomainService>();
}
}
}
@royto
Copy link
Author

royto commented Feb 23, 2018

Use Container.RegisterType<IEnumerable<IDomainService>, IDomainService[]>(); to be able to get IEnumerable ...

via https://stackoverflow.com/questions/1961549/resolving-ienumerablet-with-unity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment