IOC in WPF/WCF

It makes sense to take advantage of IOC in WCF, because all WCF services are parallel, and usually WCF service suppose to behave like a wrapper to Domain service which might needs a repository which needs an NHibernate session… How to new up those dependencies? IOC is the easiest way. And it becomes the new evil global.

In WPF, we’ve already got an un-avoidable global main window, or shell view in MVVM. Adding IOC just introduces more overhead. Even further Caliburn.Micro framework forces developer to implement a bootstrapper acting as the wrapper to the actual IOC container, the only dependency in this bootstrapper is the shell view model. If your shell view model has dependencies, you need to set them up in your underlying container. To me, this is a chicken-egg question.

 public class StructureMapBootstrapper : Bootstrapper<IShellViewModel>
    {

        protected override void Configure()
        {
            ObjectFactory.Initialize(x => x.AddRegistry<WpfDependencyRegistry>());
        }

        protected override object GetInstance(System.Type service, string key)
        {
            return ObjectFactory.GetInstance(service);
        }

    }

// StructureMap is not available in Silverlight yet, use SimplerCotainer from Caliburn instead in SL
   public class SilverlightBootstrapper : Bootstrapper<IShellViewModel>
    {
        private SimpleContainer _container;

        protected override void Configure()
        {
            _container = new SimpleContainer();

            _container.RegisterSingleton(typeof(IMessageBox), null, typeof(SlMessageBox));
            _container.RegisterSingleton(typeof(IProductSearchTask), null, typeof(ProductSearchTask));
            _container.RegisterSingleton(typeof(IProductCrudTask), null, typeof(ProductCrudTask));

            _container.RegisterSingleton(typeof(IShellViewModel), null, typeof(ShellViewModel));

        }

        protected override object GetInstance(Type service, string key)
        {
            return _container.GetInstance(service, key);
        }
    }

A better solution might be to use poor man injection in shell view model to new up all the dependencies in it’s no-arg ctor. This will remove any IOC usuage from WPF/Silverlight project, so UI developer can relief from framework hassle, and concentrate on their spinning button work.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s