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.GetControllerInsta开发者_如何学Pythonnce(
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..
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.
For Silverlight you may use PRISM framework with custom IoC container.
Autofac has built in support for silverlight: http://weblogs.asp.net/dwahlin/archive/2010/01/03/using-autofac-as-an-ioc-container-in-silverlight-applications.aspx
精彩评论