Castle Windsor Tutorial Part 3 – Dynamic Proxy (Interceptors)

Download Example

Inversion of Control – Interceptors

In the third part of this series looking at Castle Windsor we will take a look at the idea of Interceptors. Interceptors (or Dynamic Proxies as they are called in Castle) are an implementation of AOP (Aspect Oriented Programming). This allows us to “intercept” calls to methods and “proxy” the call and in the process “inject” our own code.

Using the example from the first tutorial we will create a simple interceptor to wrap the calls to a method and write the interception out to the console window.

All interceptors need to implement the IInterception interface. This specifies a single method needs to exist with the signature void Intercept(IInvovation obj) here is an example of it in use.

public class MyIntercept : IInterceptor {
    public void Intercept(IInvocation invocation) {
        Console.WriteLine(">> intercepted in <<");
        invocation.Proceed();
        Console.WriteLine(">> intercepted out <<");
    }
}

Lets start by adding the code above to our classes.cs file (from Tutorial 1)

We now need to register the Interceptor with the container just like all the other components. Here is the code to do this.

container.Register(Component.For<IInterceptor>().ImplementedBy<MyIntercept>().Named("myinterceptor"));

our installer should now look like this.

using Castle.MicroKernel.Registration;
using Castle.DynamicProxy;

namespace IOCExample
{
    public class Installers : IWindsorInstaller
    {
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            container
                .Register(Component.For<IInterceptor>().ImplementedBy<MyIntercept>().Named("myinterceptor"))

                .Register(Component.For<IStartPageModel>().ImplementedBy<StartPageModel>().LifestyleTransient())

                .Register(Component.For<IStartPageViewModel>().ImplementedBy<StartPageViewModel>().LifestyleTransient())

                .Register(Component.For<IHeading>().ImplementedBy<Heading>().LifestyleTransient())

                .Register(Component.For<IShell>().ImplementedBy<Shell>().LifestyleTransient())

                .Register(Component.For<MainWindow>().LifestyleTransient());

        }
    }
}

No we have to tell the interceptor what to intercept, we dont want it doing it to everything, so lets add the interception attribute to our classes. Add the following to the class declaration of the Shell class

	[Interceptor("myinterceptor")]

it should look like this.

    [Interceptor("myinterceptor")]
    public class Shell : IShell
    {
        public MainWindow window { get; set; }

        public void Run()
        {
            window.Show();
        }
    }

Now add the same declaration to the StartPageViewModel class, which should then look like this

    [Interceptor("myinterceptor")]
    public class StartPageViewModel : IStartPageViewModel
    {

        public IStartPageModel viewmodel { get; set; }

        public StartPageViewModel(){}

        public IStartPageModel Get()
        {
            viewmodel.Heading.Caption = "App-Code.Net";
            viewmodel.SubHeading.Caption = "Hello World";
            return viewmodel;
        }
    }

If you run the example code you should see the output of the interception in the Debug Output Window.

	>> intercepted in StartPageViewModel <<
	>> intercepted out StartPageViewModel <<
	>> intercepted in Shell <<
	>> intercepted out Shell <<

So far we have seen that we can attribute our classes to intercept the calls to methods on them. Its also possible to do this from the installation.
we can do this by adding the following statement to the registration of our classes.

.Interceptors(InterceptorReference.ForKey("myinterceptor")).Anywhere  

as an example the Shell class registration would look like this. I’ve formatted the registration so that its readable.

.Register(Component
	.For<IShell>()
	.ImplementedBy<Shell>()
	.LifestyleTransient()
	.Interceptors(InterceptorReference.ForKey("myinterceptor")).Anywhere)

The code below shows this in context. Note: i commented out the attribute on the Shell class so that this would work

using Castle.MicroKernel.Registration;
using Castle.DynamicProxy;
using Castle.Core;

namespace IOCExample
{
    public class Installers : IWindsorInstaller
    {
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            container
                .Register(Component.For<IInterceptor>().ImplementedBy<MyIntercept>().Named("myinterceptor"))

                .Register(Component.For<IStartPageModel>().ImplementedBy<StartPageModel>().LifestyleTransient())

                .Register(Component.For<IStartPageViewModel>().ImplementedBy<StartPageViewModel>().LifestyleTransient())

                .Register(Component.For<IHeading>().ImplementedBy<Heading>().LifestyleTransient())

                //.Register(Component.For<IShell>().ImplementedBy<Shell>().LifestyleTransient())

                .Register(Component.For<IShell>().ImplementedBy<Shell>().LifestyleTransient().Interceptors(InterceptorReference.ForKey("myinterceptor")).Anywhere)

                .Register(Component.For<MainWindow>().LifestyleTransient());

        }
    }
}

When we registered the interceptor we gave it a name “myinterceptor”, it is this name that we are referencing on the Interceptor(“myinterceptor”)] attribute and also in the component registration InterceptorReference.ForKey(“myinterceptor”) the .Anywhere setting at the end of the registration where abouts in the interception chain that it should be place. For more information on this please refer to Castle Windsor Dynamic Proxy (Interceptors)

Download Example

47 Comments

  1. I have been exploring for a little for any good quality articles or blogs
    in this type of area . Exploring the web I ultimately stumbled upon this site.
    Reading this content I’m glad to show that I have an incredibly good uncanny feeling that I came upon exactly what I wanted.

    Feel free to visit my web blog: ipad 2 keyboard

  2. One of the automobile capital teams stated earlier, lenders
    that are online offer easiest and the best auto loan agreement procedure.

    My homepage auto loans bad credit online (Emmett)

  3. Fantastic web site. Plenty of helpful information here.
    I am sending it to a few friends ans also sharing in delicious.
    And naturally, thanks on your effort!

    Also visit my blog post :: Iso certification in dubai (Pearl)

  4. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment iis added I get several e-mails
    with the same comment. Is there any way you can remove
    people from that service? Thanks a lot!

  5. Howdy, i read your blog from tijme to time and i own a similar one and i was
    just wondering if you gget a loot of spam responses? If so how do you protect against it, any plugin or anything you can recommend?

    I get so much lately it’s driving me insane so any support is very much
    appreciated.

  6. I know this if off topic but I’m looking into starting my own weblog and
    was curious what all is needed to get setup?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet savvy so I’m not 100% sure.
    Any tips or advice would be greatly appreciated. Thanks

    Take a look at my web page: Locksmith Portland

  7. Exceptional post however I was wanting to know if you could
    write a litte more on this subject? I’d be very thankful if you could elaborate a little bit more.
    Cheers!

    Also visit my web blog – gta 5 solo money glitch – Rosario,

  8. I was very pleased to discover this website.
    I want to to thank you for ones time due to this wonderful read!!
    I definitely liked every part of it and I have
    you saved to fav to look at new information on your web site.

    Here is my website :: Adele

  9. I do not even қnow how I ended up here, but I thought
    thiѕ post was great. I don’t know who yoս are but definitely
    you’re going to a famous blogger if you are not already ;
    ) Cheers!

  10. Do you mind if Ι quote a few of your posts as long as I pr᧐νide
    credit and sߋurces back to your weblog? My website is
    in the very same niche as yours ɑnd my users
    ԝould truly benefit from some of the information you prеsent here.
    Please let me know if this okay with you. Thanks!

  11. Asҝing questions arе really good thіng if you arе not
    understanding anything completely, but this article offers nice understanding yet.

  12. Hmm it ⅼooks like your bⅼog ate my fiгst comment (it was super long)
    so I guess I’ll ϳust sum it սp wһat I wrote and say, I’m thoroughly enjoying yоur blog.

    I too am an aspiring blog writer but I’m stіll new
    to the whole thing. Do you have any tips and hints for
    newbie bloց writers? I’d really appreciɑte іt.

  13. Ahaa, its gߋod conversation ɑbοut this post at this place at this website,
    I have read all that, so at this time me also commenting at this place.

  14. Whats up vеry nice web site!! Мan .. Excellеnt ..
    Wonderful .. I ԝill bookmark yoᥙr web site and take the feeds additionally?
    I’m satisfied to search out so many hеlpful information rigһt here in the publish, we want
    work out eхtra techniques on thiѕ regard, thɑnk you
    for sharing. . . . . .

  15. Unquestіonably believe that that you said.
    Your fɑvourite reason appeared to be at the internet the easiest factor to take note of.
    I say to you, I definitely get ɑnnoyed whilst other people
    think about worгies that they plainly do not recognize about.
    You controlled to hit the nail upon the highest as
    well as defіned out the entire thing with no neеd side effect ,
    other folks could take a signal. Will probably be again to get more.
    Thank you

  16. I’m not that much of a internet reɑdeг to be honest but
    your blogs rеally nice, keep іt up! I’ⅼl go ahead and Ьookmarҝ your site to come back
    later. All the best

  17. Wһat’s ᥙp, everүthing is going well here and ofcourse every
    one is sharing facts, that’s in fact excellent, keep ᥙp writing.

  18. I was cᥙrious if you ever thought of changing the pɑge layout of your website?

    Its νery well wrіtten; I love what youve got to
    ѕay. But maybe you could a littlе more in the way of
    content so people ⅽould connect with it better.
    Youve got an awful lot ߋf text for only having 1 or 2 pictures.
    Maybe you cоuld space it out Ƅetter?

  19. Wһen s᧐meone writes an article һe/she қeeps the plan of
    a user in his/her brain that how a user can be aware of it.
    Thuѕ that’s why this paragraph is great. Thanks!

Comments are closed.