I am attempting to mimic some stuff from Orchard CMS in my own app using unity..
Okay so what I am trying to do is this...
Lets say I have a marker interface called IDependency..
public interface IDependency{ }
I then have several interfaces hanging off of this...
public interface ICustomerService : IDependency { }
public interface ICustomerRepository : IDependency { }
and then have some classes too...
public class CustomerService : ICustomerService {
public CustomerService(ICustomerRepository customerRepo){ }
}
public class SomOtherCustomerService : ICustomerService {
public CustomerService(ICustomerRepository customerRepo){ }
}
public class NicksController : Controller {
public NicksController(IEnumerable<ICustomerService> customerServices) { }
}
public class NicksSecondController : Controller {
public NicksSecondController(IEnumerable<ICustomerService> customerServices) { }
}
What I have so far..
var container = new UnityContainer();
container
.ConfigureAutoRegistration()
.ExcludeSystemAssemblies()
//.Include(If.Implements<IDependency>, Then.Register()
//.As<IDependency>().UsingLifetime<PerResolveLifetimeManager>())
.Include(t =>
typeof(IDependency).IsAssignableFrom(t), (type, builder) =>
{
builder.RegisterType(type);
foreach (var interfaceType in type.GetInterfaces()
.Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
builder = builder.RegisterType(interfaceType, type);
}
})
.ApplyAutoRegistration();
Im falling down on the injecting of an IEnumerable in to my NicksSecondController... Any Ideas??
Cheers, Nick
Out of the box Unity only knows how to resolve arrays. Have a look at the TecX project on codeplex. It contains a custom extension that teaches the container to handle
IEnumerable<T>
,IList<T>
andICollection<T>
as well. The code can be found in TecX.Unity (folder Collections).