Registering/Resolving interfaces with generics

May 12, 2009 at 2:09 PM

Hello,

Assuming i have an interface IRepository<T> where T means a database entity, and that i have implementations for each entity named Repository<T>.

Can i, somehow, tell Unity to resolve all my IRepository<Car> and IRepository<Person> as Repository<Car> and Repository<Person> ? I believe i've seen Castle Windsor do this, but i'm not sure.

Thanks,

MF.

May 22, 2009 at 9:48 AM
Edited May 22, 2009 at 9:50 AM

Hi,

Correct me if I'm wrong, but this is what you are searching for:

IUnityContainer container = new UnityContainer();
container
.RegisterType(typeof(IRepository<>), typeof(Repository<>));

Hope this helps ;)

May 26, 2009 at 8:53 PM

Thank you, that helped a lot :)

It works. I can even register a CarRepository as IRepository<Car> implementation and have it resolved when asking Unity to resolve an IRepository<Car>, which is perfect!

Dec 8, 2009 at 3:00 PM
MFelicio wrote:

Thank you, that helped a lot :)

It works. I can even register a CarRepository as IRepository<Car> implementation and have it resolved when asking Unity to resolve an IRepository<Car>, which is perfect!

Besides: is there any way of doing this (see above) in an xml configuration?

Best wishes,

Karsten

Dec 9, 2009 at 9:00 AM

Translating it to configuration: (assuming IRepository is in the Common assembly and Repository is in the Data assembly)

<type type="Common.IRepository`1, Common" mapTo="Data.Repository`1, Data" />

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Dec 11, 2009 at 5:19 AM
AvanadeSupport wrote:

Translating it to configuration: (assuming IRepository is in the Common assembly and Repository is in the Data assembly)

<type type="Common.IRepository`1, Common" mapTo="Data.Repository`1, Data" />

[..]

Almost - what I was actually looking for is this:

<type type="Common.IRepository`1[[Car]], Common", mapTo="Data.CarRepository, Data" />
<!-- with CarRepository : IRepository<Car> -->

Should be valid (?); at least, as expected, it gives me a CarRepository when resolving an IRepository<Car>.

Best wishes,

Karsten

Dec 11, 2009 at 6:27 AM

Yes, it is also valid.

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com