开发者

Castle Windsor fluent registration : AllTypes and type forwarding

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(type开发者_高级运维of(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()
        })
);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜