views:

247

answers:

1

Given the following classes/interfaces :

class Repository<T> : IRepository<T> {}
class UserRepository : Repository<User>, IUserRepository {}

Is there a simple way to transform this :

container.Register(
    Component.For<IUserRepository>()
        .Forward<IRepository<User>>()
            .ImplementedBy<UserRepository>()
    );

Into an automatic registration through AllTypes ? So far I'm missing type forwarding.

container.Register(
    AllTypes.FromAssemblyContaining(typeof(IUserRepository))
        .BasedOn(typeof(Repository<>))
        .WithService.Select((t, b) => new List<Type>  {
            t.GetInterfaces().Where( x => !x.IsGenericType ).FirstOrDefault()
        })
);

But with the type forwarding ? So this will work :

container.Resolve<IUserRepository>().GetType() == container.Resolve<IRepository<User>>().GetType()

The following code doesn't quite work, as FirstInterface() returns the IRepository<User> :

container.Register(
    AllTypes.FromAssemblyContaining(typeof(IUserRepository))
        .BasedOn(typeof(Repository<>))
        .WithService.FirstInterface()
);

Edit : I was pretty close, so in my case :

container.Register(
    AllTypes.FromAssemblyContaining(typeof(IUserRepository))
        .BasedOn(typeof(Repository<>))
        .WithService.Select((t, b) => new List<Type>  {
            t.GetInterfaces()
        })
);
+1  A: 

I may not be accurate since I write it from memory:

There's a WithService.Select overload. You can pass custom method there that returns IEnumerable. You can then use it to match your types accordingly.

Krzysztof Koźmic
Yes, found it soon after I wrote the question !
mathieu

related questions