Creating a simple logging Interceptor using NInject 3.0

8. oktober 2013 20:52 by martijn in .net, DRY, ninject

One of the really cool aspects of Depency Injection is the ability to add functionality without changing existing code. A typical example of this might be implementing INotifyPropertyChanged or logging method calls. Using NInject 3.0 Interceptors it is very easy to do this. The interceptor intercepts all calls to the resolved object and allows you to add logging or whatever code you want to run. In NInject 3.0 the methods you intercept do NOT have to be virtual as well :) So how to set it up...

Getting the right assemblies.

Using Nuget just get NInject.Extensions.Interception.Linfu. This will also setup NInject 3.0 and NInject.Extensions.Interception.

 

Creating the logging Interceptor

This is just a sample interceptor that logs using Console.Writeline. Normally you would call something like Log4Net or your preferred logging framework. Implementing IInterceptor means you have to implement a Intercept method. The Intercept method gets a invocation as a parameter. By invocation.Proceed() the original method gets called. The logger first logs the method being called and the arguments it is called with. After the invocation.Proceed() it logs the result of the method call. The interceptor is pretty simple and can certainly be improved by creating nicer more custom messages.

public class LoggingInterceptor : IInterceptor

    {

        public void Intercept(IInvocation invocation)

        {

            var methodName = invocation.Request.Method.Name;

            try

            {

                var parameterNames = invocation.Request.Method.GetParameters().Select(p => p.Name).ToList();

                var parameterValues = invocation.Request.Arguments;

 

                var message = string.Format("Method {0} called with parameters ", methodName);

                for (int index = 0; index < parameterNames.Count; index++)

                {

                    var name = parameterNames[index];

                    var value = parameterValues[index];

                    message += string.Format("<{0}>:<{1}>,", name, value);

                }

 

                //log method called

                LogMessage(message);

 

                //run the intercepted method

                invocation.Proceed();

 

                //log method return value

                if (invocation.Request.Method.ReturnType != typeof(void))

                {

                    LogMessage(string.Format("Method {0} returned <{1}>", methodName, invocation.ReturnValue));

                }

 

            }

            catch (Exception ex)

            {

                var message = string.Format("Method {0} EXCEPTION occured: {1} ", methodName, ex);

                LogMessage(message);

                throw;

            }

        }

 

        private static void LogMessage(string message)

        {

            Console.WriteLine(string.Format("{0:HH:mm} {1}", DateTime.Now, message));

        }

    }

 

 

Adding the logging interceptor to your NInject Configuration

In your kernel configuration you can add interceptors to your bindings like this :

kernel.Bind<IService>().To<Service>().Intercept().With<LoggingInterceptor>();

Now when getting a IService using Kernel.Get<IService> the logginginterceptor will be interception all method calls :) A working sample console application can be found here: 

SampleLogging.rar (2.86 mb)

SampleLogging.rar (2.86 mb)

 

 

 

Dane 11-10-2013 18:15:14 United States #
Dane

hello there and thank you for your information � I have definitely picked up anything new from right here. I did however expertise a few technical issues using this site, since I experienced to reload the website a lot of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I'm complaining, but slow loading instances times will often affect your placement in google and could damage your high quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my e-mail and could look out for much more of your respective intriguing content. Make sure you update this again soon..

Backlinks list Keywordlists and SEO tools 16-10-2013 12:42:06 United States #
Backlinks list Keywordlists and SEO tools

The Zune concentrates on being a Portable Media Player. Not a web browser. Not a game machine. Maybe in the future it'll do even better in those areas, but for now it's a fantastic way to organize and listen to your music and videos, and is without peer in that regard. The iPod's strengths are its web browsing and apps. If those sound more compelling, perhaps it is your best choice.

Constance Cossel 17-10-2013 12:29:49 United States #
Constance Cossel

"wow, awesome blog post. Great."

Handmade Jewelry 3-11-2013 02:01:32 United States #
Handmade Jewelry

Thanks for all your valuable labor on this website. Gloria delights in acquiring into investigations and it is obvious why. A lot of people hear all concerning the dynamic method you present powerful guidelines on this website and as properly boost response from other individuals on the topic matter so our own daughter is truly studying lots of issues. Take pleasure in the remaining portion with the new year. You are the 1 carrying out a splendid job.

Handmade Jewelry 3-11-2013 04:40:48 United States #
Handmade Jewelry

Do you mind if I quote a couple of your articles as long as I give credit and sources back to your internet site? My weblog is in the quite same niche as yours and my visitors would surely benefit from lots of the data you offer here. Please let me know if this alright with you. Thanks a lot!

Handmade Jewelry 3-11-2013 18:16:00 United States #
Handmade Jewelry

i’m certain all of you're truly impressive and since for beginners like me….i managed to get to the correct destination for a read about whatever wanted…

Handmade Jewelry 3-11-2013 19:13:07 United States #
Handmade Jewelry

You will find some fascinating closing dates on this article but I don’t know if I see all of them middle to heart. There’s some validity nonetheless I’ll take preserve opinion until I appear into it further. Excellent write-up , thanks and we want extra! Added to FeedBurner as effectively

Handmade Jewelry 3-11-2013 21:19:49 United States #
Handmade Jewelry

Youre so cool! I dont suppose Ive learn anything like this before. So excellent to search out someone with some authentic tips on this subject. realy thank you for beginning this up. this web internet site is 1 thing that’s required on the internet, someone with somewhat originality. helpful job for bringing something new towards the internet!

Connor Douglas 6-11-2013 09:48:54 #
Connor Douglas

{

Zachariah 7-11-2013 18:57:58 United States #
Zachariah

Glad I  noticed this on google .

Molly Eitniear 7-11-2013 20:13:49 United States #
Molly Eitniear

I don't speak english very much but i love this blog. It is interesting.

Alamat Supplier Tas Ori Mangga Dua 10-11-2013 07:15:20 United States #
Alamat  Supplier Tas Ori Mangga Dua

When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

Eagle Safety 12-11-2013 08:12:24 United States #
Eagle Safety

Hi there buddie, I just wanted to share with you that your content was useful to me. I had been able to take the information you actually so kindly shared and also put it to use. Your blog content genuinely worked for me and I wish to tell your committed viewers they really have someone who's their thoughts fixed. Thank you once again for this terrific posting. I have bookmarked this on my favorite internet book-marking site and i also suggest all the others do the very same.

Letter From Santa 4-12-2013 13:44:13 United States #
Letter From Santa

Hi! I've been following your blog for a while now and finally got the courage to go ahead and give you a shout out from  Lubbock Texas! Just wanted to say keep up the excellent job!

Santa letters 6-12-2013 01:22:48 United States #
Santa letters

Hi there! I know this is somewhat off topic but I was wondering if you knew where I could get a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having trouble finding one? Thanks a lot!

Santa Clause Letters 6-12-2013 22:24:05 United States #
Santa Clause Letters

Hey there just wanted to give you a brief heads up and let you know a few of the pictures aren't loading properly. I'm not sure why but I think its a linking issue. I've tried it in two different internet browsers and both show the same results.

Lanell 12-12-2013 15:51:00 United States #
Lanell

WONDERFUL Post.thanks for share..extra wait .. �

types of depression 17-12-2013 03:28:26 United States #
types of depression

I really like what you guys are up too. Such clever work and reporting! Keep up the fantastic works guys I've incorporated you guys to  blogroll.  <a href=http://depression.usabestads.com>depression help</a>

price for gold 17-12-2013 13:09:38 United States #
price for gold

Post writing is also a excitement, if you be acquainted with then you can write if not it is difficult to write.  <a href=http://gold.usabestads.com>gold sellers</a>

Free Sample Cosmetics 18-12-2013 06:35:04 United States #
Free Sample Cosmetics

Wow, marvelous weblog format! How lengthy have you ever been blogging for? you made running a blog glance easy. The total look of your web site is great, as smartly as the content!  <a href=http://cosmeticstest.net>free beauty samples</a>

dental hygiene 19-12-2013 01:38:00 United States #
dental hygiene

Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how could we communicate?  <a href=http://dentalcare.adsuse.com>affordable dental care</a>

att uverse coupons 20-12-2013 02:05:44 United States #
att uverse coupons

Hey! I know this is kinda off topic but I'd figured I'd ask. Would you be interested in trading links or maybe guest writing a blog article or vice-versa? My site addresses a lot of the same topics as yours and I think we could greatly benefit from each other. If you're interested feel free to send me an email. I look forward to hearing from you! Fantastic blog by the way!

copd 20-12-2013 03:50:39 United States #
copd

Thanks for sharing such a pleasant opinion, piece of writing is nice, thats why i have read it completely  <a href=http://asthma.adsuse.com>symptoms of copd</a>

types of cancer 21-12-2013 15:28:23 United States #
types of cancer

Very quickly this site will be famous among all blog people, due to it's fastidious articles or reviews  <a href=http://cancer.adsuse.com>ovarian cancer symptoms</a>

what causes cellulite 21-12-2013 20:41:32 United States #
what causes cellulite

Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with some pics to drive the message home a little bit, but instead of that, this is excellent blog. A fantastic read. I will definitely be back.  <a href=http://cellulite.adsboards.com>cellulite treatments</a>

credit repair dallas 22-12-2013 21:33:37 United States #
credit repair dallas

I'm gone to convey my little brother, that he should also visit this website on regular basis to get updated from latest reports.  <a href=http://creditrepair.usabestads.com>credit repair attorney</a>

best debt consolidation 23-12-2013 22:52:32 United States #
best debt consolidation

I constantly emailed this web site post page to all my contacts, as if like to read it next my contacts will too.  <a href=http://debtconsolidation.usabestads.com>trinity debt consolidation</a>

depression facts 26-12-2013 02:44:28 United States #
depression facts

Hey! I know this is kind of off topic but I was wondering which blog platform are you using for this website? I'm getting fed up of Wordpress because I've had issues with hackers and I'm looking at options for another platform. I would be great if you could point me in the direction of a good platform.  <a href=http://depression.usabestads.com>am i depressed</a>

emergency dental care 26-12-2013 12:46:09 United States #
emergency dental care

I'm really loving the theme/design of your website. Do you ever run into any browser compatibility issues? A small number of my blog readers have complained about my site not operating correctly in Explorer but looks great in Chrome. Do you have any suggestions to help fix this issue?  <a href=http://dentalcare.adsuse.com>cosmetic dentistry</a>

facts about gold 27-12-2013 00:29:41 United States #
facts about gold

Greetings from Florida! I'm bored to tears at work so I decided to browse your blog on my iphone during lunch break. I love the info you provide here and can't wait to take a look when I get home. I'm shocked at how fast your blog loaded on my cell phone .. I'm not even using WIFI, just 3G .. Anyhow, wonderful blog!  <a href=http://gold.usabestads.com>gold sellers</a>

acne rosacea 27-12-2013 17:23:49 United States #
acne rosacea

Nice post. I was checking continuously this weblog and I'm inspired! Extremely helpful info specifically the closing phase Smile I take care of such information much. I used to be looking for this certain information for a very long time. Thanks and best of luck.   <a href=http://acne.adsuse.com>acne treatment</a>

what causes asthma 14-1-2014 16:03:22 United States #
what causes asthma

My brother suggested I might like this website. He was totally right. This post truly made my day. You cann't imagine simply how much time I had spent for this information! Thanks!  <a href=http://asthma.adsuse.com>asthma inhalers</a>

cellulite treatment 15-1-2014 05:12:31 United States #
cellulite treatment

Terrific post however I was wondering if you could write a litte more on this topic? I'd be very grateful if you could elaborate a little bit further. Cheers!  <a href=http://cellulite.adsboards.com>cellulite reduction</a>

information on depression 15-1-2014 12:44:46 United States #
information on depression

If you desire to take a great deal from this article then you have to apply such techniques to your won web site.  <a href=http://depression.usabestads.com>depression help</a>

facts about gold 16-1-2014 08:20:15 United States #
facts about gold

Have you ever considered writing an ebook or guest authoring on other blogs? I have a blog based on the same subjects you discuss and would love to have you share some stories/information. I know my subscribers would value your work. If you're even remotely interested, feel free to send me an email.  <a href=http://gold.usabestads.com>gold prices</a>

Julie 6-2-2014 23:57:53 United States #
Julie

Love to find posts that have good information like this, thanks

une voyance maintenant 10-2-2014 07:00:21 United States #
une voyance maintenant

voyance par telephone en direct perpignan<br/>Consulter notre superbe post : <a href="http://www.paradiseradio;fr">voyance gratuite immediate</a>

Acheter e-cigarette ego-t 11-2-2014 19:07:18 United States #
Acheter e-cigarette ego-t

Consulter mon magnifique post : <a href="www.macigarette-electronique.com">http://macigarette-electronique.com</a><br/>

Stories 17-2-2014 00:04:25 United States #
Stories

I think this internet site contains some real superb information for everyone Laughing. "Nothing surely is so disgraceful to society and to individuals as unmeaning wastefulness." by Count Benjamin Thompson Rumford.

hostingoweseo.org 17-2-2014 16:47:57 United States #
hostingoweseo.org

Hey would you mind sharing which blog platform you're using? I'm planning to start my own blog soon but I'm having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for something completely unique.  P.S Sorry for being off-topic but I had to ask!

website 28-2-2014 20:34:02 United States #
website

You have brought up a very  excellent  points ,  appreciate it for the post.

Marla 1-3-2014 05:05:56 United States #
Marla

Nice to see information that can help me is still online.

Veda 2-3-2014 02:44:50 United States #
Veda

Nice job on presenting the information, this was very helpful.

Jolanda 5-3-2014 06:14:48 United States #
Jolanda

I am sure everyone that has come to your website has appreciated it as much as me, keep up th good informative work.

princess cut 5-3-2014 21:09:58 United States #
princess cut

Love to find posts that have good information like this, thanks

best teeth 8-3-2014 08:59:46 United States #
best teeth

I love your presentation, keep writing an providing information like this.

his response 12-3-2014 01:54:42 United States #
his response

Enjoyed  looking at  this, very good stuff,  regards . "It is well to remember that the entire universe, with one trifling exception, is composed of others." by John Andrew Holmes.

tootpaste 22-3-2014 08:30:58 United States #
tootpaste

Great post I wish to make use of more of your information, time ready.

how to get a big penis 4-4-2014 08:19:55 United States #
how to get a big penis

I like the helpful information you supply in your articles. I�ll bookmark your blog and check once more here frequently. I'm reasonably certain I�ll be told plenty of new stuff right here! Good luck for the next!

go right here 4-4-2014 14:01:34 United States #
go right here

Thanks  for helping out, good  info .

iseng 3 9-4-2014 10:13:09 United States #
iseng 3

Hi, Neat post. There is an issue together with your site in internet explorer, may test this? IE still is the marketplace leader and a big portion of other people will pass over your excellent writing because of this problem

iseng 2 9-4-2014 18:40:16 United States #
iseng 2

Excellent post. I was checking continuously this blog and I'm inspired! Very useful info specifically the remaining phase Smile I handle such info a lot. I was seeking this particular information for a very long time. Thanks and good luck.

Brian 10-4-2014 15:42:52 United States #
Brian

Very nice, thanks for the post.

Brian 10-4-2014 21:24:19 United States #
Brian

Very nice, thanks for the post.

stories 2-5-2014 22:23:17 United States #
stories

Simply  a smiling visitor  here to share the love (:, btw great   design and style .

Nichol 19-5-2014 10:39:39 United States #
Nichol

You info has been of terrific assistance, good work

Pantofi Barbatesti 18-6-2014 12:43:44 United States #
Pantofi Barbatesti

Given that I to begin with wrote around MBT sneakers at <strong><a href="incaltaminte-mopiel.ro/.../category&path=18_46"; title="Pantofi Barbatesti">Pantofi Barbatesti</a></strong>, a whole lot includes adjusted relating to the brand name, and the inventor and founder consists of still left the small business. Involving true buyers, assessments of MBT footwear are Incredibly combined. If by yourself're looking at a few of MBT footwear, I strongly motivate oneself in the direction of way too examine the opinions remaining inside solution toward the immediately after written content, and discuss in direction of your medical doctor right before sporting any style of shoe that is thus substantially substitute versus what on your own're utilised towards, or in direction of deal with any design of agony or issue.

website and your business 29-3-2015 17:46:06 United States #
website and your business

It's hard to find knowledgeable people on this topic, but you sound like you know what you're talking about! Thanks

Property listings San Francisco 30-3-2015 13:19:19 United States #
Property listings San Francisco

Thank you on your assist!

hills anzac of centenary 31-3-2015 01:26:31 United States #
hills anzac of centenary

Thanks for your exciting article. Other thing is that mesothelioma is generally caused by the inhalation of fibres from asbestos fiber, which is a very toxic material. It truly is commonly observed among personnel in the building industry who have long exposure to asbestos. It is caused by living in asbestos covered buildings for a long time of time, Genes plays an important role, and some persons are more vulnerable to the risk than others.

Spencer Duma 2-4-2015 10:22:24 United States #
Spencer Duma

My developer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he's tryiong none the less. I've been using WordPress on numerous websites for about a year and am concerned about switching to another platform. I have heard good things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any help would be greatly appreciated!

Danyel Kresal 4-4-2015 19:25:43 United States #
Danyel Kresal

My programmer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the expenses. But he's tryiong none the less. I've been using Movable-type on several websites for about a year and am anxious about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can import all my wordpress content into it? Any help would be greatly appreciated!

Roxane Witthuhn 5-4-2015 00:24:42 United States #
Roxane Witthuhn

I love what you guys are usually up too. This type of clever work and exposure! Keep up the superb works guys I've added you guys to our blogroll.

web link 7-4-2015 13:25:52 United States #
web link

As soon as I  detected  this  web site  I went on reddit to share some of the love with them.

Jeramy 9-4-2015 09:36:35 United States #
Jeramy

Hi JanJamm and Sam,

Stefania Wiebold 12-4-2015 17:55:12 United States #
Stefania Wiebold

Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thank you for lunch!

Sharla Stoudt 19-4-2015 15:33:54 United States #
Sharla Stoudt

Hello there! This post could not be written much better! Reading through this article reminds me of my previous roommate! He continually kept talking about this. I am going to forward this article to him. Fairly certain he will have a very good read. Thanks for sharing!

Dropbox Tips Tricks 29-4-2015 04:30:04 United States #
Dropbox Tips Tricks

Good post! We will be linking to this particularly great article on our site. Keep up the good writing.

��C 15-5-2015 18:26:24 United States #
��C

merci pour ces informations

Celina Kiesz - HR Software 25-5-2015 05:14:09 United States #
Celina Kiesz - HR Software

Whats up this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding know-how so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

iphone 5c 28-5-2015 21:58:52 United States #
iphone 5c

<p>Thank you so much for stopping by and sharing Bryan! Really awesome how you volunteer to help adults better connect with prayer and the Torah! </p><p>Ramadan Karim to you too and I wish you continued success as well!</p><p>Maryam</p>

Yukiko Verdi 18-6-2015 05:31:03 United States #
Yukiko Verdi

Hi, I live in USA. I’ve decided to make this profile to make guide how to Penis Growth Guide. I’d like to chat a lot with different people, share pics, play games and have some fun ;) Anyway, if you are interested in knowing you can see at http://bitly.com/1e5QC9L

Efrain Sarwar 28-6-2015 02:16:29 United States #
Efrain Sarwar

I congratulate, your idea is useful

hindi songs 15-7-2015 03:39:57 United States #
 hindi songs

xnxx. a free mp3 download site for artists & news ...

hybrid battery 23-7-2015 12:17:24 United States #
hybrid battery

I just added this feed to my bookmarks. I have to say, I really enjoy reading your blogs. Keep it up!

Bok Familia 25-7-2015 10:59:04 United States #
Bok Familia

killer job

music social network 25-7-2015 11:09:01 United States #
music social network

free dance mp3 download site

Bert Nola 6-8-2015 11:45:37 United States #
Bert Nola