c# - 在与 Windsor 的依赖项中使用相同的参数值

标签 c# castle-windsor

甚至不确定这是否可以完成,可能需要重新考虑整个事情,但我想在这样做之前我会问。

好的,我有一个带有以下构造函数的存储库类

    public Repository(ISessionManager sessionManager, string dbName)
    {
        this.sessionManager = sessionManager;
        this.dbName = dbName;
    }

目前,在应用程序中任何需要使用存储库的地方,它都会使用依赖注入(inject),并且存储库会像这样注册到容器中。

Component.For<IRepository<User, int>>().ImplementedBy<Repository<User, int>>()
                     .DependsOn(Dependency.OnValue("dbName", "admin")),

我想要做的是将数据库名称的设置提升到将使用存储库的服务级别。

例如有构造函数的服务

public SecurityService(ITransactionFactory transactionFactory,
                       IRepository<User, int> userRepository,
                       string dbName)

我希望将参数 dbName 注册到针对 ServiceService 的容器中,并在注入(inject)参数 userRepository 时传递该值。

因此,如果另一个服务需要使用具有不同数据库的相同存储库,那么在注册时会提供一个新名称。

这可能吗?

最佳答案

我不知道有什么方法可以完全按照您的要求进行操作,但是使用命名注册可能会让您以一种更温莎的方式达到相同的最终目标——“正确”。

例如,以下两个注册可以同时存在:

Component.For<IRepository<User, int>>()
         .ImplementedBy<Repository<User, int>>()
         .DependsOn(Dependency.OnValue("dbName", "admin")
         .Named("adminRepositoryRegistration")

Component.For<IRepository<User, int>>()
         .ImplementedBy<Repository<User, int>>()
         .DependsOn(Dependency.OnValue("dbName", "user")
         .Named("userRepositoryRegistration")

然后您可以连接您的服务以依赖于 Windsor 中的特定注册。例如,这个将绑定(bind)到第一个注册:

Component.For<IUserService>()
         .ImplementedBy<UserService>()
         .DependsOn(Dependency.OnComponent("userRepository", "userRepositoryRegistration")

这将绑定(bind)到第二个:

Component.For<ISecurityService>()
         .ImplementedBy<SecurityService>()
         .DependsOn(Dependency.OnComponent("adminRepository", "adminRepositoryRegistration")

总的来说,我觉得它提供了一个更简洁的解决方案,因为它处理了 DI 注册中的所有 依赖项配置,而不是留下任何未完成的部分以包含在实际服务中,并且允许您根据需要路由依赖项。

关于c# - 在与 Windsor 的依赖项中使用相同的参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026718/

相关文章:

c# - Unity 4(IOC) + MVC 5 在启动期间无法解析类型

c# - 如何防止根据条件执行 Controller 操作?

C# (429) 请求过多

c# - CaSTLe windsor 添加条件依赖

c# - CaSTLe 不断给我一个 System.TypeLoadException : Method 'myMethod' does not have implementation?

c# - 顶点属性缓冲区绑定(bind)到错误的属性

c# - 应用程序长时间空闲后,EF Core AddAsync 和 SaveChangesAsync 稍微变慢

c# - 创建 CaSTLe.Windsor 拦截器的问题

.net - 温莎城堡 : How to wire up a component to a factory property rather than method

asp.net-mvc - CaSTLeWindsor 也填充了类字段