Arthis
Arthis

Reputation: 2293

IOC and Silverlight

In mvc asp.net, I can override a factory to create my controllers, and so put a reference to my IOC just here. Doing So every interface needed by the constructor of my controllers will be feeded by my IOC .

Is there some common way to do it using Silverlight? At the moment I only found to use the kernel of Ninject everywhere :

public partial class MyUserControlSL   
{
    public MyUserControlSL()
    {
        DataContext = new MyViewModel(Kernel.Get<IMyRepository>());
        InitializeComponent();
    }
}

eg using StructureMap and MVC:

public class ControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(
        RequestContext requestContext, Type controllerType)
    {
        IController result = null;
        try
        {
            if (controllerType != null)
            {
                result = ObjectFactory.GetInstance(controllerType) 
                    as Controller;
            }
            else
            {
                return base.GetControllerInstance(
                    requestContext, controllerType);
            }
        }
        catch (StructureMapException)
        {
            System.Diagnostics.Debug.WriteLine(
                ObjectFactory.WhatDoIHave());
            throw;
        }

        return result;
    }
}

public AController(IServiceA serviceA)
{
    if (serviceA == null)
    {
        throw new Exception("IServiceA cannot be null");
    }
    _ServiceA = serviceA;
}

public ServiceA(IRepositoryA repository)
{
    if (repository == null)
    {
        throw new Exception(
            "the repository IRepositoryA cannot be null");
    }

    _Repository = repository;
}

Thanks for your help, please ask if it is not clear..

Upvotes: 3

Views: 560

Answers (3)

Jan Christian Selke
Jan Christian Selke

Reputation: 370

In Silverlight you should use a bootstrapper at composition root to wire up your entire object graph. It could be the Application class app.xml.cs and look similar to

public partial class App : Application
{
   private void Application_Startup(object sender, StartupEventArgs e)
   {
       Bootstrapper bootstrapper = new Bootstrapper();
       bootstrapper.Run();
   }
}

In general this should be sufficant but if you need a separate Factory class for your views, take a look at Keeping the DI-container usage in the composition root in Silverlight and MVVM.

Upvotes: 2

Lyubomyr Vyhovskyy
Lyubomyr Vyhovskyy

Reputation: 11

For Silverlight you may use PRISM framework with custom IoC container.

Upvotes: 1

Related Questions