c# - 为构造函数类指定固定值和容器中的其他变量

标签 c# asp.net-mvc castle-windsor

我有一个阶段,一些接口(interface),还有注册部分。问题是我需要将一些参数定义为固定参数,将其他参数定义为变量。

interface IDoSomething {
 void DoWork();
}

interface IDoMath(){
 void DoWork();
}

interface IBehaviorBusiness{
 void Do();
}

class BehaviorBusiness {
 ...
 public BehaviorBusiness(IDoSomething doSomething, IDoMatch doMatch, string connection){};
 ...
}

windsor容器是否可以在声明中定义参数连接,并从容器中获取IDosomethingIDoMatch

 container.Register(
   Component.For<IDoSomething>()
   ...
 }

 container.Register(
   Component.For<IDoMatch>()
   ...
 );

这是具体问题。

 container.Register(
   Component.For<IBehaviorBusiness>()
   .ImplementedBy<BehaviorBusiness>()
   .DependsOn(Dependency.OnComponent<IDoSomething, [default]>(),
              Dependency.OnComponent<IDoMatch, [default]>(),
              Dependency.OnValue("connection", connectionString))
    .LifeStyle.Transient
   );

如果存在,哪个是正确的语法?

最佳答案

如果连接字符串来自您的应用程序设置,则使用 Dependency.OnAppSettingsValue() :

container.Register(
    Component.For<IBehaviorBusiness>()
    .ImplementedBy<BehaviorBusiness>()
    .DependsOn(Dependency.OnAppSettingsValue("connection", "connectionString"))
    .LifeStyle.Transient
);

此处,“connection”是类构造函数中的参数名称,“connectionString”是应用程序设置(即 Web.Config)中连接字符串值的键。您不需要指定其他值,Windsor 会像往常一样解析它们。

关于c# - 为构造函数类指定固定值和容器中的其他变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490601/

相关文章:

c# - 使用自定义错误页面维护错误信息

dependency-injection - 比较温莎城堡、Unity 和 StructureMap

c# - 设计简单的代码优先电影数据库(多对多)EF

c# - 无法加载dll : Module cannot be found

c# - 在 For 循环而不是 Foreach Asp MVC 5 中显示模型结果

c# - 如何使用 Windsor 将依赖项注入(inject)自定义 RoleProvider?

multithreading - 在 CaSTLe Windsor 上注册服务/组件是线程安全的吗?

c# - 将所有流量转发到 http 代理(隧道)

asp.net - 如何访问 Microsoft.Owin.Security.xyz OnAuthenticated 上下文 AddClaims 值?

c# - 带有特殊字符的 ASP.NET MVC 身份电子邮件/用户名