开发者

Dynamically adding generic services from one concrete implementation using Castle Windsor

开发者 https://www.devze.com 2023-03-12 11:49 出处:网络
I\'m using Castle Windsor, and I\'ve got the following: public class NhibernateRepository<T> : IRepository<T>

I'm using Castle Windsor, and I've got the following:

public class NhibernateRepository<T> : IRepository<T>
{
    public NHibernateRepository(...)
    {
        ...
    }

}

I'd like to use the Fluent Windsor API To register one service for each of my d开发者_StackOverflow中文版omain models

That is, I would like to dynamically register IRepository<Order>, IRepository<Customer>, IRepository<Article> etc using NHibernateRepository<T> where T is then exchanged for the concrete type in each instance.

I've got something like this:

container.Register(AllTypes.FromThisAssembly().Where(x => x.Namespace == "DITest.Repository").WithService.Select(...Something...)

But I'm not sure if this can even be done (AllTypes does after all imply that I want to register multiple types).

Any Windsor Guru out there?


Trivial with Windsor:

container.Register(Component.For(typeof(IRepository<>))
          .ImplementedBy(typeof(NHibernateRepository<>)))

Windsor will automagically close the generic types with any given type argument.

Note that the non-generic overloads of For and ImplementedBy are used only because of a language limitation - it is not valid C# to specify open generic types as types arguments (i.e. For<IRepository<>> would not compile).

More info on the official documentation wiki.

0

精彩评论

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