views:

79

answers:

2

I have a class with a constructor that looks like this:

public TimedWorker(int timerInterval, Action execute, ILogger logger)

I am using the Castle Windsor fluent configuration and whilst the config below works, I am concerned about the way I am resolving Action. Is there a better way so that I am not always resolving the action delegate to the same thing?

Component
  .For<IWorker>()
  .ImplementedBy<TimedWorker>()
  .DependsOn(new { timerInterval = TimerInterval })
  .LifeStyle.Transient,

Component.For<Action>()
  .Instance(() => Resolve<SomeService>().SomeMethod())
  .LifeStyle.Transient,

Component.For<ILogger>()
  .ImplementedBy<TraceLogProvider>()
  .LifeStyle.Singleton
+1  A: 

[UPDATE]

Ok, in this case Mauricio's solution is the best way to go.


There's nothing wrong with the approach. If you want more flexibility than .Instance gives you, use .UsingFactoryMethod.

What is exactly your concern here?

Krzysztof Koźmic
My main concern is that my code assumes that I only have to resolve one Action and in the future, should another component require a different Action dependency, my code will no longer work.
zaph0d
Perhaps if you gave it a name and use service overrides it would be more viable? You can also try this idea: http://kozmic.pl/archive/2009/04/09/convention-based-dependency-injection-with-castle-microkernelwindsor.aspx instead of service overrides, although be sure to limit your resolver to only Action delegates
Krzysztof Koźmic
thanks. that is exactly what I needed.
zaph0d
+3  A: 

If you don't need the Action anywhere else you could use DynamicParameters:

Component
  .For<IWorker>()
  .ImplementedBy<TimedWorker>()
  .DynamicParameters((kernel, parameters) => {
    parameters["timerInterval"] = TimerInterval;
    parameters["execute"] = new Action(kernel.Resolve<SomeService>().SomeMethod);
  })
  .LifeStyle.Transient, ...
Mauricio Scheffer
Fluent API registration docs: http://using.castleproject.org/display/IoC/Fluent+Registration+API
Mauricio Scheffer