Using strongly-typed configuration parameters in Windsor Installer
I've been cracking my head over installing a Windsor container using a custom configuration object. It seems simple, but apparently there's something important I'm just not getting. I'll be grateful if you could help me fill this gap.
I have a configuration class:
class MyConfiguration
{
int SomeIntValue;
DateTime SomeDateValue;
Action<string> SomeActionValue;
}
I want to pass these configuration values as constructor parameters into the registered implementations. I guess the registration should look something like:
public class MyInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Reg开发者_如何学JAVAister(Component.For<IFoo>.ImplementedBy<Foo>
.Parameters(Parameter.ForKey("parameter1").Eq( INSERT VALUE HERE (?) );
}
}
So how do I take these values and pass them into the installer? Should I use this IConfigurationStore
parameter? If so, how do I fill it up and what do I do with it?
Besides, it seems like all the configurations objects can only store string values, so how can I pass values which are not strings (such as DateTime
)?
Thanks and have a great weekend.
In the huge majority of cases you shouldn't have to explicitly register a constructor argument. The auto-wiring feature should be able to take care of that for you automatically. This will make your code less brittle and thus more maintainable.
So, the best you can do is simply to register MyConfiguration with the container. If this there's only a single registration of the type (the normal scenario), the container can unambiguously resolve any request for the type. Thus, if another class takes MyConfiguration as a constructor parameter, Castle Windsor will automatically match them for you. You don't need to specify this explicitly.
However, there are cases where you need to explicitly assign a particular parameter value. For those cases you can use ServiceOverrides. That might look something like this:
container.Register(Component.For<MyConfiguration>().Named("myConfig"));
container.Register(Component
.For<IFoo>()
.ImplementedBy<Foo>()
.ServiceOverrides(new { parameter1 = "myConfig" }));
If you need to assign a specific instance, you can instead use DependsOn:
var myConfig = new MyConfig();
container.Register(Component
.For<IFoo>()
.ImplementedBy<Foo>()
.DependsOn(new { parameter1 = myConfig }));
if you are trying to pass a type value, like an integer, string, enum etc then go with second option given by Mark..
int val = 23;
container.Register(Component
.For<IFoo>()
.ImplementedBy<Foo>()
.DependsOn(new { parameter1 = val }));
精彩评论