4

I have a collection of services that I want to register with Castle Windsor (version 3.0 RC1) using the fluent registration technique.

I want all of them except for a particular one to use the transient lifestyle and that one I want to be a singleton, so I do this:

container.Register(AllTypes
                       .FromThisAssembly()
                       .InSameNamespaceAs<IMyService>()
                       .WithServiceDefaultInterfaces()
                       .ConfigureIf(s => s.Implementation == typeof(MyService),
                                    s => s.LifestyleSingleton(),
                                    s => s.LifestyleTransient()));

The problem I have with that is that I am using typeof(MyService) in the first parameter of ConfigureIf, but I would prefer it if I could use IMyService to determine whether it is a singleton or not (i.e. it does not matter what the implementation is, it should always be a singleton). Is that somehow possible?

kmp
  • 10,535
  • 11
  • 75
  • 125
  • 1
    perhaps this could help? [How to determine if a type implements a specific generic interface type](http://stackoverflow.com/questions/503263/how-to-determine-if-a-type-implements-a-specific-generic-interface-type) – oleksii Dec 14 '11 at 16:13
  • perfect thank you! I changed the first parameter to s => typeof(IMyService).IsAssignableFrom(s.Implementation) and that worked fine. – kmp Dec 14 '11 at 16:20
  • Cool, can you post it as an answer and then accept it? – oleksii Dec 14 '11 at 16:23

1 Answers1

4

With many thanks to oleksii, who suggested looking at this question: How to determine if a type implements a specific generic interface type in the comments on the question, the answer to this is to do the following:

container.Register(AllTypes
                   .FromThisAssembly()
                   .InSameNamespaceAs<IMyService>()
                   .WithServiceDefaultInterfaces()
                   .ConfigureIf(s => typeof(IMyService).IsAssignableFrom(s.Implementation),
                                s => s.LifestyleSingleton(),
                                s => s.LifestyleTransient()));
Community
  • 1
  • 1
kmp
  • 10,535
  • 11
  • 75
  • 125