根据 appsetting 值注册组件?
Register Components Based on appsetting value?
Castle windsor 是否提供更简洁或推荐的方法来根据 app.config/web.config 中的 appsettings 值执行注册?我现在正在做的事情的例子如下
if (ConfigurationManager.AppSettings["UseFakeEmailService"] == "true")
{
container.Register(Component.For<IEmailService>().ImplementedBy<EmailService>().IsFallback().LifestyleTransient());
container.Register(Component.For<IEmailLogger>().ImplementedBy<EmailLogger>().LifestylePerThread());
}
else
{
container.Register(Component.For<IEmailService>().ImplementedBy<FakeEmailService>().IsFallback().LifestyleTransient());
container.Register(Component.For<IEmailLogger>().ImplementedBy<FakeEmailLogger>().IsFallback().LifestyleTransient());
}
有多种方法可以清理这种文字。首先想到的是声明一个工厂方法作为创建组件的方式:
Component.For<IEmailService>().UsingFactoryMethod(() => (configValue ? new EmailService() as IEmailService: new DummyEmailService() as IEmailService))
如果您真的想要花哨的东西,或者如果您有很多 类 遵循这种模式,您可以查看自定义 resolvers,它可以帮助您确定 [=26] =] 在运行时。
还有IsDefault
过滤机制可以帮助您确定默认要解析的组件:
container.Register(
Component.For<IDummy>().ImplementedBy<TestDummy>().IsDefault(t => isTestMode == true)
);
但是如果您只想注册与您的模式相关的类型,那么您做对了。您也许可以将安装推送到 IWindsorInstaller
中以将其隔离,但我知道没有其他机制可以处理它。
编辑:我应该更仔细地看一下,有 conditional registration mechanisms
在我看来,如果你想使用 XML 配置注册依赖项,那么你应该使用 Windsor XML Configuration.
的另一个例子
<components>
<component
id="notification"
service="Acme.Crm.Services.INotificationService, Acme.Crm"
type="Acme.Crm.Services.EmailNotificationService, Acme.Crm"
</component>
</components>
Castle windsor 是否提供更简洁或推荐的方法来根据 app.config/web.config 中的 appsettings 值执行注册?我现在正在做的事情的例子如下
if (ConfigurationManager.AppSettings["UseFakeEmailService"] == "true")
{
container.Register(Component.For<IEmailService>().ImplementedBy<EmailService>().IsFallback().LifestyleTransient());
container.Register(Component.For<IEmailLogger>().ImplementedBy<EmailLogger>().LifestylePerThread());
}
else
{
container.Register(Component.For<IEmailService>().ImplementedBy<FakeEmailService>().IsFallback().LifestyleTransient());
container.Register(Component.For<IEmailLogger>().ImplementedBy<FakeEmailLogger>().IsFallback().LifestyleTransient());
}
有多种方法可以清理这种文字。首先想到的是声明一个工厂方法作为创建组件的方式:
Component.For<IEmailService>().UsingFactoryMethod(() => (configValue ? new EmailService() as IEmailService: new DummyEmailService() as IEmailService))
如果您真的想要花哨的东西,或者如果您有很多 类 遵循这种模式,您可以查看自定义 resolvers,它可以帮助您确定 [=26] =] 在运行时。
还有IsDefault
过滤机制可以帮助您确定默认要解析的组件:
container.Register(
Component.For<IDummy>().ImplementedBy<TestDummy>().IsDefault(t => isTestMode == true)
);
但是如果您只想注册与您的模式相关的类型,那么您做对了。您也许可以将安装推送到 IWindsorInstaller
中以将其隔离,但我知道没有其他机制可以处理它。
编辑:我应该更仔细地看一下,有 conditional registration mechanisms
在我看来,如果你想使用 XML 配置注册依赖项,那么你应该使用 Windsor XML Configuration.
的另一个例子<components>
<component
id="notification"
service="Acme.Crm.Services.INotificationService, Acme.Crm"
type="Acme.Crm.Services.EmailNotificationService, Acme.Crm"
</component>
</components>