Created
January 22, 2018 10:29
-
-
Save royto/c108ed4cb60c38b57298df21d18e5ffe to your computer and use it in GitHub Desktop.
Unity - DI - Inject Multiple interface implementations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Demo.Service | |
{ | |
public class DomainServiceService | |
{ | |
public DomainServiceService(IDomainService[] domainServices) | |
{ | |
foreach (var service in domainServices) | |
{ | |
var name = service.GetName(); | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use
Container.RegisterType<IEnumerable<IDomainService>, IDomainService[]>();
to be able to get IEnumerable ...via https://stackoverflow.com/questions/1961549/resolving-ienumerablet-with-unity