Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

IoC for Windows Phone: Ninject

DZone's Guide to

IoC for Windows Phone: Ninject

· Mobile Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

As promised in one of my previous posts, I will spend some time explaining the differences between different Inversion of Control (IoC) methods supported by Silverlight for Windows Phone. This post is about Ninject. I will also try to compare several IoC implementations in one of my future articles.


Before making the tutorial, I will mention few facts regarding Ninject in general.

  • Ninject is a famous dependency injector .NET
  • You can download Ninject from their Website
  • You can extend Ninject functions with Extensions
  • Ninject is also supported by Silverlight and Windows Phone 7
  • Ninject supports Constructor, Properties and Method injection
  • Ninject supports 4 injection scopes: Scope, Singleton, Thread, Transient

But let us not waste much time on facts and get directly to our tutorial for Windows Phone.

Setup

Download Ninject for Windows Phone from the following website. Create new default Windows Phone project in Visual Studio and add Ninject for Windows Phone references(DLLs) there.

Creating simple Data Providers

Lets assume our product has both test and production environments. Each of them has it’s own implementation inherited from a single interface: ITextDataProvider.

public interface ITextDataProvider
{
    string GetText();
}

And the implementations are:

public class ProductionDataProvider : ITextDataProvider
{
    public string GetText()
    {
        return "production text";
    }
}
 
public class TestTextDataProvider : ITextDataProvider
{
    public string GetText()
    {
        return "test text";
    }
}

Creating an IoC Container

The container is also pretty simple. It consists of an instance of StandardKernel class, Initialize method and generic Get method, which returns an instance with injected elements based on Type parameter. Initialize method simply binds different implementations depending on current project Build action(Debug, Release) to ITextDataProvider type.

public static class IoCContainter
{
    private static readonly IKernel Kernel = new StandardKernel();
 
    public static void Initialize()
    {
        #if DEBUG
 
        Kernel.Bind<ITextDataProvider>().To<TestTextDataProvider>();
 
        #else
 
        Kernel.Bind<ITextDataProvider>().To<ProductionDataProvider>();
 
        #endif
    }
 
    public static T Get<T>()
    {
        return Kernel.Get<T>();
    }
}

Initializing the IoC Container

Now we need to initialize the IoC container somewhere and probably the most suitable location for that would be App.xaml.cs events: Application_Launching and Application_Activated that run every time the application starts.

// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
    IoCContainter.Initialize();
}
 
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
    IoCContainter.Initialize();
}

Creating a ViewModel

Hopefully, you've already been introduced to Model-View-ViewModel(MVVM) pattern that is quite popular in Silverlight world. If not, then there is plenty of information in the internet. For the ViewModel you need to add a property of ITextDataProvider type and add an [Inject] attribute to it. This property will be injected inside Kernel. Also you need to enter a very basic Property that returns a text to be displayed in UI.

public class NinjectSampleViewModel
{
    [Inject]
    public ITextDataProvider TextDataProvider { get; set; }
 
    public string TextToDisplay
    {
        get { return TextDataProvider.GetText(); }
    }
}

Creating a View

Final step is to create a View(or Page) to display the results. I have created a default Windows Phone XAML page for that and slightly modified ContentPanel element by adding a TextBlock with Text property Binding inside.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <TextBlock x:Name="tbText" Text="{Binding TextToDisplay}" />
</Grid>

As for the codebehind I have also modified it a little bit with assigning DataContext property with our ViewModel using IoCContainer class.

public NinjectSampleView()
{
    InitializeComponent();
    DataContext = IoCContainter.Get<NinjectSampleViewModel>();
}

Results

After running the application you will see either “production text” or “test text” displayed depending on your Build Action.

You can find the source code inside EugeneDotnetIoCSamples Project inside EugeneDotnetWPCodeSamples GitHub project:

eugenedotnet github windows phone project

 



Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:

Published at DZone with permission of Jevgeni Tšaikin. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}