Showing posts with label Ninject. Show all posts
Showing posts with label Ninject. Show all posts

Thursday, June 25, 2015

Poor man's interceptors: passthrough proxies

So let's say this is my greate setup:


And I want to log calls to the service without putting ugly logging lines inside the service or the calling object. How do I do this?

Well, you could go all the way with Ninject Interceptors - the way I normally do it:



Code here. Get both Nuget.Exensions.Interceptors and either the Castle or LinFu proxy package ( don't forget those ! ).

OK - that's nice - that's elegant. But I realised that there's also a more lightweight alternative to this - writing a passthroughproxy:


So now I have two implementations of IMyService: the PassThroughProxy and the MyService. The passthrough passes the call through to the injected IMyService but allows for that call to be overridden. That's what I've done in the LogAspect.
The LogAspect overrides the call - logs the call and calls its base method to propagate the call down to MyService.

Hooking this up goes as follows:



The reason I built something like this, is because I was trying to listen in on events. You can do the same thing for events, where you build a pass through proxy that propagates the events, but also logs. And I couldn't listen in on these with interceptors.

Code here

Tuesday, October 14, 2014

Excellent IoC comparison benchmark for .NET

I was Googling around to see how much the performance suffers from dependency injection with interceptors, I came across this excellent post by Daniel Palme, who compares a bunch of IoC containers for .NET.

Turns out, Ninject isn't all that fast. We've been using it for all our projects, but after reading this post, I'll be looking into LightInject. It seems to support all my use cases: MVC, WebAPI ( with InRequestScope ) and interceptor support.






Monday, February 4, 2013

Using Ninject to inject session variables into controller properties

According to our JAVA developer, JAVA spring can inject session variables into controller properties. So - I was triggered to see if I could hack something together that resembles this behavior in C#, using Ninject. So here's a quick thing that I put together:
    internal class StandardKernelWithSessionResolution : StandardKernel
    {
        public override IEnumerable Resolve(Ninject.Activation.IRequest request)
        {
            if (request.Target != null && HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session[request.Target.Name] != null)
            {
                Log.Debug("Property {0} is being injected from session", request.Target.Name);
                return new List() { HttpContext.Current.Session[request.Target.Name] };
            }
            return base.Resolve(request);
        }
    }
In your MVC application, you will need to use StandardKernelWithSessionResolution() as opposed to the StandardKernel() call. Also, you will need to instantiate the session variable once, but after that you're good:
    public class HomeController : Controller
    {
        [Inject]
        public Person SessionInjectedPerson { get; set; }

        public ActionResult Index()
        {
            this.SessionInjectedPerson = new Person();
            return View(this.SessionInjectedPerson);
        }

        public ActionResult UpdatePerson()
        {
            this.SessionInjectedPerson.Name = this.SessionInjectedPerson.Name + " > ";
            return this.View("Index",this.SessionInjectedPerson);
        }
It's not very well tested and you it works on the fact that the session entry name is the same as the property, however - it might save you some time.

Sunday, February 3, 2013

Zero implementation PHP API Wrapper in C#

The MoneyMedic API wrapper NuGet package that I wrote in December doesn't actually implement the methods of the API. All the methods actually look something like this:

    internal class MoneyMedicAPI : IMoneyMedicApi
    {
        ...
        public get_invoices_response get_invoices(string api_key, 
                                                  MoneyMedicEnum.SortInvoicesBy sortby, 
                                                  MoneyMedicEnum.SortDir sortdir)
        {
            throw new NotImplementedException();
        }
    }

When figuring out how to implement the wrapper I obseved:

  • All API calls result in a URL call with a query string that holds the method parameters and values. Like https://www.moneymedic.eu/api/[METHOD_NAME/?[PARAMETER_NAME]=[PARAMETER_VALUE]&....etc....
  • The JSON or XML response will need to be parsed into an instance of some response class


Therefore I decided to use the following setup:

  • A method call on the IMoneyMedicAPI interface is being intercepted
  • The intercepted method name matches the actual method name, the parameter names match the actual parameter names ( although StyleCop doesn't like this too much ).
  • The interceptor creates the MoneyMedic URL from intercepted method name + creates the query string from the parameter names and their corresponding values.
  • Using JSON.NET, the result is parsed to a result object, that corresponds to the information in the documentation and returns this to the caller.


And thus the actual implementation is never used or called - hence the NotImplementedExceptions that will never be thrown

Here's the interceptor:
// -------------------------------------------------------------------------------
// 
//   2012 Jochen van Wylick
// 
// -------------------------------------------------------------------------------

namespace MoneyMedicAPI
{
    using Ninject.Extensions.Interception;

    /// 
    /// The money medic API interceptor.
    /// Intercepts calls to the MoneyMedicAPI.
    /// 
    public class MoneyMedicApiInterceptor : IInterceptor
    {
        #region IMethodInterceptor Members

        /// 
        /// The MoneyMedic interceptor.
        /// 
        /// 
        /// The invocation.
        /// 
        public void Intercept(IInvocation invocation)
        {
            // Get the parameter collection
            var parameters = invocation.Request.Method.GetParameters();

            // Get the argument collection
            var arguments = invocation.Request.Arguments;

            // Invoke the API call and return the value
            invocation.ReturnValue = MoneyMedicApiHelper.InvokeApiCall(
                invocation.Request.Method.Name, parameters, arguments, invocation.Request.Method.ReturnType);
        }

        #endregion
    }
}

This made the wrapper very easy to implement. Furthermore I could use it for other wrappers if I wanted but still provide IntelliSense to the caller.

Saturday, December 1, 2012

MoneyMedic API

I'm proud to anounce that I published my first NuGet package today. It's a wrapper for the MoneyMedic API. In order to get started with the MoneyMedic API, follow these steps:

1. Get the NuGet package

See the NuGet pacakge page

2. Load the MoneyMedic API module into your Ninject kernel 

The API is built as a Ninject module. I'm using interceptors for the API calls - so you need Ninject, Interceptors and load the API module into your kernel:

3. Start using the API 

For instance - getting the list of invoices in your account: