I just released the first pre-release bits for WP7 support in Ninject. You can download them here. If you encounter any issues, please let me know. I have included signed and unsigned binaries in debug and release configurations.

Unit testing isn’t very easy for WP7. It was bizarre trying to debug the issues. The exact code that returns whether one type is assignable to another returns false in WP7. If you are trying to target WP7 and are familiar with Silverlight, you need to check out this site to see what may hurt you; the section on reflection is rather painful. These are two of my favorites:

  • Open generics are not supported in Silverlight for Windows Phone.
  • The equality (==) operator for two equal MethodInfo objects does not return true in Silverlight for Windows Phone.

One thing to note is that this code is directly off the master branch for the 2.1 release. The 2.1 release has an enhanced resolution algorithm that may be a little different that what you previously expected – if you get an exception, you were most likely doing something ambiguous that Ninject wants straightened out. I will be blogging more about this later, but the binding resolution should now better handle what you are asking it to do.

{ 1 comment }

Disclaimer: I am neither an expert in TopShelf nor Quartz, this is just me trying to plug them together with Ninject.

The fist thing we need to have in order to use Quartz is to create a job that will be executed. We will call ours the VerifyEmailServerJob.

public class VerifyEmailServerJob : IJob
{
    #region Implementation of IJob

    public void Execute( JobExecutionContext context )
    {
        // TODO: Verify the email server is working correctly...
    }

    #endregion
}

Now that we have a job to run, we will create a windows service that will create the job details and schedule the job. The windows service essentially acts as a host for the jobs.

public interface IWindowsService
{
    void Start();
    void Stop();
}

public partial class MonitoringService : ServiceBase, IWindowsService
{
    private readonly JobManager _jobManager;
    private readonly List<IScheduler> _schedulers = new List<IScheduler>();

    public MonitoringService( JobManager jobManager )
    {
        _jobManager = jobManager;
        InitializeComponent();
    }

    public void Start()
    {
        // TODO: Pull from config file.
        var trigger = new CronTrigger( "name", "group", "0 0 4/8 * * MON-FRI" );
        IScheduler scheduler = _jobManager.Add<VerifyEmailServerJob>( trigger );
        _schedulers.Add( scheduler );
    }

    protected override void OnStop()
    {
        _schedulers.ForEach( scheduler => scheduler.Shutdown( false ) );
        _schedulers.Clear();
    }
}

In order to inject our services into the jobs, we need to take control of the job activation pipeline. Quartz allows us to do this by using a implementation of IJobFactory. In my example I am injecting a creation callback function that will use the Ninject kernel to activate the job and add any dependencies without the IJobFactory knowing of the kernel. I am also throwing in my own JobManager to cut down on the amount of code I need to write to add a job. But note that we have to tell the scheduler which JobFactory to use when activating.

public class JobFactory : IJobFactory
{
    private readonly Func<Type, IJob> _creationCallback;

    public JobFactory( Func<Type, IJob> creationCallback )
    {
        _creationCallback = creationCallback;
    }

    #region Implementation of IJobFactory

    public IJob NewJob( TriggerFiredBundle bundle )
    {
        JobDetail jobDetail = bundle.JobDetail;
        Type jobType = jobDetail.JobType;
        var job = _creationCallback( jobType );
        return job;
    }

    #endregion
}

public class JobManager
{
    private readonly IJobFactory _jobFactory;
    private readonly ISchedulerFactory _schedulerFactory;

    public JobManager( ISchedulerFactory schedulerFactory, IJobFactory jobFactory )
    {
        _schedulerFactory = schedulerFactory;
        _jobFactory = jobFactory;
    }

    public IScheduler Add<T>( Trigger trigger ) where T : IJob
    {
        IScheduler scheduler = _schedulerFactory.GetScheduler();
        scheduler.JobFactory = _jobFactory;
        scheduler.Start();
        var jobDetail = new JobDetail( typeof (T).Name, typeof (T) );
        scheduler.ScheduleJob( jobDetail, trigger );
        return scheduler;
    }
}

Now with out jobs, triggers, and service foundation, all we need to do is configure TopShelf to run our service and configure our kernel to inject our dependencies.

internal static class Program
{
    private static void Main( string[] args )
    {
        using ( IKernel kernel = CreateKernel() )
        {
            RunConfiguration cfg =
                RunnerConfigurator.New(
                    x =>
                    {
                        x.SetDisplayName( "Monitoring Service" );
                        x.SetServiceName( "Monitor" );
                        x.SetDescription( "Monitoring Service" );
                        x.ConfigureService<MonitoringService>( kernel );
                        x.RunAsLocalSystem();
                    } );

            Runner.Host( cfg, args );
        }
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<IJobFactory>().To<JobFactory>();
        kernel.Bind<Func<Type, IJob>>().ToConstant( type => (IJob) kernel.Get( type ) );
        kernel.Bind<ISchedulerFactory>().To<StdSchedulerFactory>();
        kernel.Bind<JobManager>().ToSelf().InSingletonScope();
        kernel.Bind<IWindowsService>().To<MonitoringService>();
        return kernel;
    }
}

public static class SyntaxExtensions
{
    public static void ConfigureService<T>( this IRunnerConfigurator runnerConfigurator, IKernel kernel )
        where T : ServiceBase, IWindowsService
    {
        runnerConfigurator.ConfigureService<T>(
            c =>
            {
                c.HowToBuildService( serviceName => kernel.Get<T>() );
                c.Named( typeof (T).Name );
                c.WhenStopped( s => s.Stop() );
                c.WhenStarted( s => s.Start() );
            } );
    }
}

That about does it! We have a service configured and controlled by TopShelf, running scheduled jobs using Quartz, and dependencies and jobs created by Ninject.

{ 0 comments }

Windows Services with Ninject and TopShelf

May 18, 2010

I was testing out TopShelf and here is an example I put together in order to have Ninject activate the services and their dependencies:
#region Using Directives

using System;
using System.ServiceProcess;
using YourCorp.Services;
using Ninject;
using Topshelf;
using Topshelf.Configuration;
using Topshelf.Configuration.Dsl;

#endregion

namespace YourCorp
{
internal static class Program
{
private static void [...]

Read the full article →

Build Systems

May 9, 2010

$:>call begin-rant
I am impeded and embittered by the current state of builds systems. I need to get ready to make Windows Phone 7 and Silverlight 4 builds, but the tooling doesn’t have support for them. On a side note, why the heck did I have to install VS2010 Express in order to get the WP7 [...]

Read the full article →

Fibonacci LINQ Sequence Generator Revisited

May 4, 2010

It was pointed out that the sequence generator could be written as an infinite sequence to allow .Skip(), .Take(), .ElementAt(), etc. Here is the infinite sequence version.
public static class Fibonacci
{
public static IEnumerable<BigInteger> Generate()
{
yield return 1;
yield return 1;

BigInteger n1 = 1, n2 = 1;
while(true)
{
BigInteger n3 = n1 + n2;
n1 = n2;
n2 = n3;
yield return n3;
}
}
}

Read the full article →

WinDgb script when debugging drivers

May 1, 2010

If you ever happen to be writing a device driver and you want to have WinDbg configured to run a set of scripts, this configuration for WINDBG.INI may be of help. If it doesn’t mean anything to you, don’t worry, nothing to see here other than pain. Replace anything in {} with your own paths [...]

Read the full article →

Fibonacci LINQ Sequence Generator

April 30, 2010

I wanted to see what could be done with the Fibonacci sequence, but I didn’t have something that played nicely with LINQ. Here is my first cut:
public static class Fibonacci
{
public static IEnumerable<BigInteger> Generate( int n )
{
return Generate( (long) n [...]

Read the full article →

Dual Posting

April 25, 2010

I will be making blog posts to more than one blog from now on. If you take a look at the IntelliTechture blog you can use the main feed or my personalized feed to see my blog posts that are not posted here. I just blogged on Parallel.For where i does not go to i++ [...]

Read the full article →

Configuring a Kinesis Ergo Advantage

April 13, 2010

I had to reset my keyboard and I had forgotten the setup that I need to do in order to get it configured the way I like it. In case anyone else ever wants to set theirs up, here is mine:

To disable tones used by Caps Lock, Keypad, and others, hold down Progrm and press [...]

Read the full article →

Parallel Matrix Multiplication with the Task Parallel Library (TPL)

March 31, 2010

About
I brushed off some old benchmarking code used in my clustering application and decided to see what I can do using today’s multi-core hardware. When writing computationally intensive algorithms, we have a number of considerations to evaluate. The best (IMHO) algorithms to parallelize are data parallel algorithms without loop carried dependencies.
You may think nothing is [...]

Read the full article →

Ninject.Extensions.MessageBroker 2.0 Released!

March 19, 2010

I am happy again to announce the release of the next Ninject extension, Ninject.Extensions.MessageBroker 2.0! You can download the release from GitHub for all supported platforms (.NET 3.5, .NETCF 3.5, SL2, SL3, MONO). Also, you can review the demo post using the extension if you are wondering how to hook it together.

Read the full article →

Ninject.Extensions.Interception 2.0.1 Released

March 19, 2010

I have just pushed new binaries and tagged the release on GitHub. There was confusion on how to deal with automatic module loading with the release that contained both proxy modules – every mailing list question pertained to this confusion, so it needed to be resolved. I have removed this release in favor of having [...]

Read the full article →

Using Ninject.Extensions.Interception Part 2 : Working with Interceptors

March 12, 2010

Overview
In Part 1 we covered the basics of the extension and introduced the IInterceptor interface. Now we can move more in depth and look at the interceptor system composed of

Custom Interceptors
Interception via Attributes

With these, we can define a rich set of interception capabilities in our applications.
Custom Interceptors
The base of the binding interception is the very [...]

Read the full article →

Using Ninject.Extensions.Interception Part 1 : The Basics

March 10, 2010

About the Extension
The Ninject interception extension relies on the DynamicProxy implementations of Castle and LinFu to generate proxy instances. The interception extension is essentially an abstraction of the proxying components leveraging Ninject’s feature set along with interception utilities.
Enabling the Extension
There are two ways to enable the extension. The easiest way is to use Ninject’s automatic [...]

Read the full article →

Ninject.Extensions.Interception 2.0 Released!

March 6, 2010

On the heels of the Ninject 2.0 release, I am happy to announce the release of the Ninject Interception Extension 2.0. This release provides API backward compatibility for the 1.5 version as well as new method interception, enhanced binding syntax, automatic property changed notification, as well as support for Castle DynamicProxy 2.2 and LinFu DynamicProxy. [...]

Read the full article →

Ninject.Extensions.Conventions Preview

February 26, 2010

I have been playing with the Ninject conventions binding extension syntax and usage model. It was originally based on the StructureMap assembly scanner, but I want to use the API in a different fashion.
I have been working on making the API more like LINQ in the way you think and use it. Here is a [...]

Read the full article →

Ninject 1.5 and 2.0 Released!

February 25, 2010

That’s right! We have officially released Ninject 1.5 and 2.0! Ninject 2.0 has been in beta for exactly one year and we are very happy to announce its release. You can download the binaries from the Ninject.org web site. Expect more posts here and on Nate’s blog with more information.
Over the next couple weeks we [...]

Read the full article →

TFS Shell Extension

January 29, 2010

If you are using the TFS Shell Extension and you get an error dialog when choosing Team Foundation Server -> Reconnect
—————————
Unable to Reconnect
—————————
Unable to connect to Team Foundation Server
—————————
OK
—————————
There is a workaround. TFS extension only supports windows credentials at the moment, so if the server is using domain authentication, you can try to open your [...]

Read the full article →

Ninject.Extensions.Interception and IAutoNotifyPropertyChanged (IANPC)

January 23, 2010

After having conversation on twitter with Jonas Folleso about an automatic INotifyPropertyChanged implementation, I couldn’t resist digging in and seeing what I can do. He also has a blog post that is definitely worth reading on this subject. He solved the same problem through the IProvider functionality in Ninject. The code is based on his initial implementation. [...]

Read the full article →

Ninject.Extensions.Interception now supports DynamicProxy2

January 23, 2010

Seeing that people wanted to use Castle DynamicProxy2 with Ninject for interception, I ported the support from Ninject 1.5 and we now have support for using DynamicProxy2 built-in for the Ninject 2.0 extension.
DynamicProxy2:
IKernel kernel = new StandardKernel(new DynamicProxy2Module());
LinFu:
IKernel kernel = new StandardKernel(new LinFuModule());
Note: Breaking Change!!!
InterceptionModule is now abstract. The proxy specific modules need to be [...]

Read the full article →