caSTLe-windsor - CaSTLe温莎流利注册: AllTypes and type forwarding

标签 castle-windsor

给定以下类/接口(interface):

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

有没有简单的方法来转换它:

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

通过 AllTypes 进入自动注册?到目前为止,我缺少类型转发。

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

但是使用类型转发?所以这会起作用:

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

下面的代码不太有效,因为 FirstInterface() 返回 IRepository :

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

编辑:我非常接近,所以就我而言:

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

最佳答案

我凭内存写的可能不准确:

有一个 WithService.Select 重载。您可以在那里传递返回 IEnumerable 的自定义方法。然后,您可以使用它来相应地匹配您的类型。

关于caSTLe-windsor - CaSTLe温莎流利注册: AllTypes and type forwarding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2503291/

相关文章:

c# - 设计 - 使用 Windsor 时应该在哪里注册对象

api - 如何访问 CaSTLe Windsor 的 Fluent Interfaces API?

c# - 在 CaSTLe Windsor 中注册同一接口(interface)的多个实现

asp.net-mvc - 使用 CaSTLe.Windsor 实现 UnitOfWork

caSTLe-windsor - 使用 Windsor 注入(inject)应用程序设置

asp.net-mvc - 对于特定的 Controller 使温莎实例化不同的类

c# - 是什么导致错误 "Looks like you forgot to register the http module CaSTLe.MicroKernel.Lifestyle.PerWebRequestLifestyleModule"?

asp.net-mvc-4 - 将 HttpContext.Current.Session 注入(inject)到拦截器/或在内部拦截器中使用时(mvc4 webapi),HttpContext.Current.Session 为 null

c# - 温莎解析 IEnumerable<IMyType>

c# - 新手 caSTLe windsor 并尝试创建我的接口(interface)的实现