Home > Development > Castle Service Overrides

Castle Service Overrides


Lets say we have created to classes that implement the IEmailService, 1 which actually sends an email and another which is a null email service which does nothing.

Look at the following registrations:

            // Email Service Management
            container.Register(Component.For<IEmailService>()
                                   .ImplementedBy<EmailService>()
                                   .Named("emailservice.default")
                                   .LifeStyle
                                   .Transient
                );
            container.Register(Component.For<IEmailService>()
                                   .ImplementedBy<NullEmailService>()
                                   .Named("emailservice.alternative")
                                   .LifeStyle
                                   .Transient
                );

Then lets say we have a notifier class that uses an IEmailService. Which one will it use. This is where service overrides come in and allow you to specifically specify the correct one to use. Look at the following example.

// Notifier
            container.Register(Component.For<INotifier>()
                                   .ImplementedBy<Notifier>()
                                   .ServiceOverrides(ServiceOverride.ForKey("emailService").Eq("emailservice.default"))
                                   .LifeStyle
                                   .Transient
                );

An important point to notice is the “emailService” is the actual parameter name in the class in either the constructor or property name and the bit in the Eq(“emailservice.default”) is the name you gave to the type when you registered it.

Make sure you name your two types when you register to ensure you can specify the correct type in the service override section.

Blair…

Advertisements
Categories: Development Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: