<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Derik Whittaker : Ninject</title><link>http://devlicio.us/blogs/derik_whittaker/archive/tags/Ninject/default.aspx</link><description>Tags: Ninject</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Convention Binding to Ninject 3 -- Resolving ‘Value Cannot be Null’ Exception</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2012/08/12/convention-binding-to-ninject-3-resolving-value-cannot-be-null-exception.aspx</link><pubDate>Sun, 12 Aug 2012 12:26:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70273</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=70273</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=70273</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2012/08/12/convention-binding-to-ninject-3-resolving-value-cannot-be-null-exception.aspx#comments</comments><description>&lt;p&gt;Recently I was creating a new &lt;a href="http://www.asp.net/mvc/mvc4"&gt;MVC4&lt;/a&gt;&amp;nbsp; application and of course I wanted to use &lt;a href="http://devlicio.us/controlpanel/blogs/posteditor.aspx/www.ninject.org"&gt;Ninject&lt;/a&gt; as my IoC container.&amp;nbsp; The first thing I did was to download and install the following NuGet packages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://nuget.org/packages/Ninject.MVC3"&gt;Ninject.MVC3&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="http://nuget.org/packages/ninject.extensions.conventions"&gt;Ninject.Extensions.Conventions&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="http://nuget.org/packages/CommonServiceLocator.NinjectAdapter"&gt;CommongServiceLocator.NinjectAdapter&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After I got these setup I opened up the NinjectWebCommon.cs class and started to add code to the RegisterServices method.&amp;nbsp; The first thing i did was to add the code below;&lt;/p&gt;
&lt;pre name="code" class="c#"&gt;            kernel.Bind(scanner =&amp;gt;
            {
                try
                {
                    scanner.FromAssemblyContaining()
                    .SelectAllClasses()
                    .BindDefaultInterface();

                    scanner.FromAssemblyContaining()
                        .SelectAllClasses()
                        .BindDefaultInterface();

                    scanner.FromAssemblyContaining()
                        .SelectAllClasses()
                        .BindDefaultInterface();
                }
                catch (Exception e) // added to try to get the exception message
                {
                    Debug.WriteLine(e);
                    throw;
                }
            });&lt;/pre&gt;
&lt;p&gt;The above code would step over the first scanner call w/ no issues, in fact if that was the ONLY statement it all worked as expected, however when it stepped onto the second scanner. call I would get the following error.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;System.ArgumentNullException: Value cannot be null. Parameter name: first&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Because I knew everything worked fine with only one scanner. call i decided to give it a go w/&amp;nbsp; creating a unique kernal.Bind for each assembly i wanted scanned as below:&lt;/p&gt;
&lt;pre name="code" class="c#"&gt;            kernel.Bind(scanner =&amp;gt; scanner.FromAssemblyContaining()
                                       .SelectAllClasses()
                                       .BindDefaultInterface());

            kernel.Bind(scanner =&amp;gt; scanner.FromAssemblyContaining()
                                       .SelectAllClasses()
                                       .BindDefaultInterface());

            kernel.Bind(scanner =&amp;gt; scanner.FromAssemblyContaining()
                                       .SelectAllClasses()
                                       .BindDefaultInterface());&lt;/pre&gt;
&lt;p&gt;This did the trick, I could now setup the bindings for multiple assemblies with no issues.&amp;nbsp; So it appears that with this version of the Extensions class for ninject you need to do each action as a unique .Bind method.&lt;/p&gt;
&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70273" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Agile/default.aspx">Agile</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/ASP.Net+MVC/default.aspx">ASP.Net MVC</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Ninject/default.aspx">Ninject</category></item><item><title>Convention Based View Model Location using Ninject in a MVVM/Silverlight Application</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2011/07/02/view-model-location-using-ninject-in-a-mvvm-silverlight-application.aspx</link><pubDate>Sat, 02 Jul 2011 11:23:53 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:67852</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=67852</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=67852</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2011/07/02/view-model-location-using-ninject-in-a-mvvm-silverlight-application.aspx#comments</comments><description>***** UPDATE *****   &lt;br /&gt;If you would like to see a video on this topic check out &lt;a href="http://dimecasts.net/Casts/CastDetails/194"&gt;Episode 194 @ Dimecasts.Net&lt;/a&gt;   &lt;br /&gt;*******************  &lt;p&gt;When building out a Silverlight application (or WPF application for that matter) the &lt;a href="http://en.wikipedia.org/wiki/Model_View_ViewModel"&gt;MVVM&lt;/a&gt; pattern is the pattern of choice for most projects I am aware of.&amp;#160; When using MVVM there is a sub pattern which is commonly used which is known as ViewModelLocator.&amp;#160; The ViewModelLocator concept basically tries to handle the repetitive task of coupling the View with its ViewModel but doing so in a way which removes any manual coding and it just ‘happens’.&lt;/p&gt;  &lt;p&gt;Now if you have done any research on the ViewModel Location I am sure you have run across countless other blog posts out there which explain how to implement in this code, and many of them are great.&amp;#160; In fact here are a few which helped me down the path of creating the code I am going to talk about in this post&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://johnpapa.net/simple-viewmodel-locator-for-mvvm-the-patients-have-left-the-asylum"&gt;Simple ViewModel Locator&lt;/a&gt; for MVVM by John Papa (this is the post which really kick started this pattern) &lt;/li&gt;    &lt;li&gt;Wiring up &lt;a href="http://blog.roboblob.com/tag/viewmodellocator/"&gt;ViewModel Locator&lt;/a&gt; w/ Silverlight &lt;/li&gt;    &lt;li&gt;MVVM and &lt;a href="http://geekswithblogs.net/bdiaz/archive/2010/03/31/kiss-and-tell---mvvm-and-the-viewmodellocator.aspx"&gt;ViewModel Location&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Another MVVM and &lt;a href="http://geekswithblogs.net/bdiaz/archive/2010/03/31/kiss-and-tell---mvvm-and-the-viewmodellocator.aspx"&gt;ViewModel Location&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://caliburnmicro.codeplex.com/"&gt;Caliburn.Micro&lt;/a&gt; has an implementation &lt;/li&gt;    &lt;li&gt;&lt;a href="http://mvvmlight.codeplex.com/"&gt;MVVMLight&lt;/a&gt; has an implementation &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;All of the above posts basically show how to implement this pattern in your application and from what I can tell all of them work and will do the job. However, none of those (minus the Caliburn.Micro) implementations fulfills the one requirement I want which is to totally remove the need to ‘wire’ the ViewModel up to your View if even via XAML.&amp;#160; I want to remove this wiring from the XAML because in my mind this still leaves me hard wiring the relationship rather than using convention based wiring.&amp;#160; One scenario in which the hard wiring could turn around and bite you is in the times where you rename the view and the view model.&amp;#160; If you fail to update your wiring code in XAML you will receive runtime errors.&lt;/p&gt;  &lt;p&gt;Here are a few examples:    &lt;br /&gt;John Papa’s Implementation&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;DataContext=&amp;quot;{Binding Source={StaticResource VMLocator}, Converter={StaticResource VMIndexerConverter}, ConverterParameter=MainPageViewModel}&amp;quot;&lt;/pre&gt;

&lt;p&gt;ViewModelLocator’s Implementation&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;    &amp;lt;UserControl.Resources&amp;gt;
        &amp;lt;ViewModels:EditUsersViewModelLocator x:Key=&amp;quot;viewModelLocator&amp;quot;  /&amp;gt;
    &amp;lt;/UserControl.Resources&amp;gt;
    &amp;lt;UserControl.DataContext&amp;gt;
        &amp;lt;Binding Source=&amp;quot;{StaticResource viewModelLocator}&amp;quot; Path=&amp;quot;ViewModel&amp;quot; /&amp;gt;
    &amp;lt;/UserControl.DataContext&amp;gt;&lt;/pre&gt;

&lt;p&gt;I wanted my implementation of toe ViewModelLocator pattern to NOT need to know anything about the actual View or the ViewModel either in the XAML or in the code behind.&amp;#160; What I wanted as the following:&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;DataContext=&amp;quot;{Binding Source={StaticResource VMLocator}, Converter={StaticResource VMIndexerConverter}}&amp;quot;&lt;/pre&gt;

&lt;p&gt;Now you may be looking at my XAML above and comparing it to the XAML from John Papa’s post and be thinking what is really different?&amp;#160; The difference is in this segment of code &lt;em&gt;ConverterParameter=MainPageViewModel &lt;/em&gt;In his example he ‘hard wires’ the ViewModel which is being used up to the page and I did not want to do that.&amp;#160; I wanted to use a standard naming convention (right, &lt;a href="http://en.wikipedia.org/wiki/Convention_over_configuration"&gt;convention over configuration&lt;/a&gt;) and allow my locator to determine the ViewModel based on the current View.&lt;/p&gt;

&lt;p&gt;So how did I implement my ViewModelLocator pattern, well lets take a look.&lt;/p&gt;

&lt;p&gt;Code for ViewModelLocator&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;public class ViewModelLocator
{   
    private static readonly IDictionary&amp;lt;type, type&amp;gt; s_viewModelCache = new Dictionary&amp;lt;type, type&amp;gt;();
        
    public Type GetViewModelTypeForView( Type viewType )
    {
        var viewModelName = ResolveViewModelName(viewType.Name).ToLower();

        // We are try to cache the types in order to remove the assembly scan hit, this is optional of course and 
	// you may not want or need this
	// One thing to point out here is that this code ASSUMES that your view and viewmodel classes are in the 
	//  same assembly.  if this is not true for your project this code will not work as expected.  We made this
	//  assumption because it is true in our project
        var foundViewModelType = GetExistingTypeFromCache(viewType) ?? (from type in viewType.Assembly.GetExportedTypes()
                                                                        where viewModelName.Equals(type.Name.ToLower())
                                                                        select type).FirstOrDefault();
    
        // this will throw a custom exception type, you can use your own if you want
        if (foundViewModelType == null) { throw new ViewModelTypeNotResolvedException(viewModelName, viewType); }

        // Add the found view and viewModel to the cache
        AddToCache(viewType, foundViewModelType);

        return foundViewModelType;
    }

    private void AddToCache(Type viewType, Type foundViewModelType)
    {
        if (!s_viewModelCache.ContainsKey(viewType))
        {
            s_viewModelCache.Add(viewType, foundViewModelType);
        }
    }

    private Type GetExistingTypeFromCache( Type viewType )
    {
        if (s_viewModelCache.ContainsKey(viewType))
        {
            return s_viewModelCache[viewType];
        }

        return null;
    }

    private string ResolveViewModelName(string viewTypeName)
    {
        var asLowerViewTypeName = viewTypeName.ToLower();

	// ***** Below is OUR product&amp;#39;s current naming conventions, replace with your own if you want *****
        // check to see if the view ends w/ &amp;quot;View&amp;quot;
        if (asLowerViewTypeName.EndsWith(&amp;quot;view&amp;quot;))
        {
            return asLowerViewTypeName.Replace(&amp;quot;view&amp;quot;, &amp;quot;ViewModel&amp;quot;);
        }

        if (asLowerViewTypeName.EndsWith(&amp;quot;usercontrol&amp;quot;))
        {
            return asLowerViewTypeName.Replace(&amp;quot;usercontrol&amp;quot;, &amp;quot;ViewModel&amp;quot;);
        }

        if (asLowerViewTypeName.EndsWith(&amp;quot;childwindow&amp;quot;))
        {
            return asLowerViewTypeName.Replace(&amp;quot;childwindow&amp;quot;, &amp;quot;ViewModel&amp;quot;);
        }

        return string.Concat(viewTypeName, &amp;quot;ViewModel&amp;quot;);
    }

    public static IDictionary&amp;lt;type, type&amp;gt; ViewModelCache { get { return s_viewModelCache; } }
}&lt;/pre&gt;

&lt;p&gt;Code for IndexConverter&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;public class IndexerConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    {
        Contract.Requires&amp;lt;ArgumentNullException&amp;gt;(value != null);

        var locator = value as ViewModelLocator;

        Contract.Assume(locator != null,
                        string.Format(
                            &amp;quot;The provided converter value was expected to be of type {0} but was provided as type {1} which is not acceptable for this converter&amp;quot;,
                            typeof(ViewModelLocator).Name,
                            value.GetType().Name));

        var viewType = GetViewType();

        var viewModelType = locator.GetViewModelTypeForView(viewType);

	// We are using the ServiceLocator pattern which is wrapping Ninject
        var viewModelInstance = ServiceLocator.Current.GetInstance(viewModelType);

        return viewModelInstance;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
        
    // This does incur a perf hit by looking at the stack trace, but in 
    //  my opinion this hit is worth it compared to having to manually wire items up
    private Type GetViewType()
    {
        var stack = new StackTrace();

        return stack.GetFrames()
            .Select(f =&amp;gt; f.GetMethod())
            .Where(m =&amp;gt; m.Name == &amp;quot;InitializeComponent&amp;quot;)
            .Select(m =&amp;gt; m.DeclaringType)
            .FirstOrDefault();
    }

}&lt;/pre&gt;

&lt;p&gt;Code needed in your App.Xaml&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;&amp;lt;MVVMLib:ViewModelLocator x:Key=&amp;quot;VMLocator&amp;quot; /&amp;gt;
&amp;lt;MVVMLib:IndexerConverter x:Key=&amp;quot;VMIndexerConverter&amp;quot; /&amp;gt;&lt;/pre&gt;

&lt;p&gt;Code for the custom Exception ViewModelTypeNotResolvedException&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;public class ViewModelTypeNotResolvedException : Exception
{
    public string ViewModelName { get; set; }
    public Type ViewName { get; set; }

    // Commented this out because i do not want to be able to create this without the VMName or the VName
    //public ViewModelTypeNotResolvedException() {}

    /// 
    /// Will build an instance of the exception and push in a default message based on the viewModelname and view properties.
    /// *** This is the lazy way to create the message ***
    /// 
    /// &lt;param name="viewModelName" /&gt;The name of the viewModel which was not able to be created or found&lt;/param&gt;
    /// &lt;param name="view" /&gt;The type for the view we were trying to bind the VM to&lt;/param&gt;
    public ViewModelTypeNotResolvedException(string viewModelName, Type view)
        : base(string.Format(&amp;quot;When trying to resolve the view model {0} it was not found in the same assembly as the view {1}&amp;quot;, viewModelName, view.Name))
    {
        ViewModelName = viewModelName;
        ViewName = view;            
    }

    /// 
    /// Will build an instance of the exception
    /// 
    /// &lt;param name="viewModelName" /&gt;The name of the viewModel which was not able to be created or found&lt;/param&gt;
    /// &lt;param name="view" /&gt;The type for the view we were trying to bind the VM to&lt;/param&gt;
    /// &lt;param name="message" /&gt;&lt;/param&gt;
    public ViewModelTypeNotResolvedException(string viewModelName, Type view, string message) : base(message)
    {
        ViewModelName = viewModelName;
        ViewName = view;
    }

    /// 
    /// Will build an instance of the exception
    /// 
    /// &lt;param name="viewModelName" /&gt;The name of the viewModel which was not able to be created or found&lt;/param&gt;
    /// &lt;param name="view" /&gt;The type for the view we were trying to bind the VM to&lt;/param&gt;
    /// &lt;param name="message" /&gt;&lt;/param&gt;
    /// &lt;param name="innerException" /&gt;&lt;/param&gt;
    public ViewModelTypeNotResolvedException(string viewModelName, Type view, string message, Exception innerException)
        : base(message, innerException)
    {
        ViewModelName = viewModelName;
        ViewName = view;
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see the code needed for this is not that complicated or difficult to implement.&amp;#160; &lt;/p&gt;

&lt;p&gt;One thing to understand with this post, I am NOT saying that the other implementations are bad or they do not work. In fact I am saying the exact opposite, they all are great and they all work and I used all their implementations as baseline for my implementation.&amp;#160; What I am saying as the other examples did not meet my EXACT needs. &lt;/p&gt;

&lt;p&gt;Please take a look at the code and let me know where I went wrong or what your thoughts are.&amp;#160; &lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=67852" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Development/default.aspx">Development</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Best+Practice/default.aspx">Best Practice</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/XAML/default.aspx">XAML</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Ninject/default.aspx">Ninject</category></item><item><title>Ninject and binding to an existing Method (or Property)</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2011/06/30/ninject-and-binding-to-an-existing-method-or-property.aspx</link><pubDate>Thu, 30 Jun 2011 12:57:05 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:67810</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=67810</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=67810</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2011/06/30/ninject-and-binding-to-an-existing-method-or-property.aspx#comments</comments><description>&lt;p&gt;Ok, this is just a cool little feature I found in &lt;a href="http://ninject.org/"&gt;Ninject&lt;/a&gt; today and I am 100% sure I may be the last person on the planet to find this but who cares.&lt;/p&gt;  &lt;p&gt;today as I was trying to get IoC implemented in our application at work I ran across the need to bind a type to an existing singleton in our application.&amp;#160; The reason for this need is 2 fold:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;I am not willing to take on the risk at this point of changing the ENTIRE application to utilize IoC &lt;/li&gt;    &lt;li&gt;This is our RIA services domain context and I do not have enough knowledge in RIA services to know a better way to do this &lt;img style="border-bottom-style:none;border-right-style:none;border-top-style:none;border-left-style:none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/wlEmoticon_2D00_smile_5F00_4618183E.png" /&gt; &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So how do you bind a type to an existing method (or property)?&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Make sure that you have the general convention based bindings setup correctly within Ninject. &lt;/li&gt;    &lt;li&gt;Rebind your time and point it to the method you want to use &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;To Rebind you simply should do&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;ninjectKernel.Rebind&amp;lt;DomainContext&amp;gt;().ToMethod(x =&amp;gt; MyClass.DomainContext); &lt;/pre&gt;

&lt;p&gt;In the above code what we are doing is Rebinding the DomainContext type to the Method on the MyClass instance.&amp;#160; This will notify Ninject to not try to create a new instance of DomainContext but rather it will invoke the method, or in my case property, on my class.&lt;/p&gt;

&lt;p&gt;I just thought this was kinda cool and wanted to share.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=67810" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Development/default.aspx">Development</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Fun+Code/default.aspx">Fun Code</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Ninject/default.aspx">Ninject</category></item><item><title>Ninject and Convention Based Assembly Bindings</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2011/06/30/ninject-and-convention-based-assembly-bindings.aspx</link><pubDate>Thu, 30 Jun 2011 11:17:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:67808</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=67808</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=67808</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2011/06/30/ninject-and-convention-based-assembly-bindings.aspx#comments</comments><description>&lt;p&gt;***** NOTE: This post was created because other &lt;a href="http://innovatian.com/2009/09/conventions-based-binding-with-ninject-2-0-2/"&gt;posts&lt;/a&gt; on the net are outdated and the ninject libraries have changed. *****&lt;/p&gt;  &lt;p&gt;When using any type of IoC container one of your goals needs to be to remove as much friction and ceremony as possible.&amp;#160; One way to do this with an IoC container is to use convention based binding based on assembly scanning.&lt;/p&gt;  &lt;p&gt;When using Ninject you can setup the container to bind via assembly scanning by using the &lt;a href="http://github.com/ninject/ninject.extensions.conventions"&gt;Ninject.Extensions.Conventions&lt;/a&gt; extension and a few lines of code.&amp;#160; Lets get rolling and learn how to do this&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Getting the software:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Get Ninject – Download your correct platform version &lt;a href="http://ninject.org/download"&gt;here&lt;/a&gt;     &lt;br /&gt;Get the Convention Extension – Download the binary or source &lt;a href="https://github.com/ninject/ninject.extensions.conventions"&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Creating the Code to do assembly scanning:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Setup your Using Statements&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;using Ninject;
using Ninject.Extensions.Conventions;&lt;/pre&gt;

&lt;p&gt;Setup The Service location&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;private void StupServiceLocation()
{
    IKernel ninjectKernel = new Ninject.StandardKernel();
    
    // The AssemblyScanner is in the Ninject.Extensions.Conventions library
    var ninjectAssemblyScanner = new AssemblyScanner();

    // Here I am setting up the scanning in the assembly which contains the given interface
    ninjectAssemblyScanner.FromAssemblyContaining&amp;lt;IMessageboxService&amp;gt;();

    // This is important, without the call to using default conventions Ninject will not know how to 
    //  bind an IFoo to the Foo instance
    ninjectAssemblyScanner.BindWithDefaultConventions();
            
    // Tell the ninject kernel to do its job
    ninjectKernel.Scan( ninjectAssemblyScanner );

    // Reach into the container and grab the instance you are looking for.
    var messageBoxService = ninjectKernel.Get&amp;lt;IMessageboxService&amp;gt;();
}&lt;/pre&gt;
OR use Lambda syntax 

&lt;pre class="c-sharp" name="code"&gt;private void StupServiceLocation()
{
    IKernel ninjectKernel = new Ninject.StandardKernel();

    // If you would rather use the lamba syntax you can use the following
    ninjectKernel.Scan( kernel =&amp;gt;
	{
    	kernel.FromAssemblyContaining&amp;lt;IMessageboxService&amp;gt;();
    	kernel.BindWithDefaultConventions();
	});

    // Reach into the container and grab the instance you are looking for.
    var messageBoxService = ninjectKernel.Get&amp;lt;IMessageboxService&amp;gt;();
}&lt;/pre&gt;

&lt;p&gt;As you can see setting up Ninject to setup it’s bindings based on assembly scanning is very easy and requires pretty much NO code.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=67808" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Development/default.aspx">Development</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Ninject/default.aspx">Ninject</category></item><item><title>Ninject.Extensions.Conventions ported to work w/ WP7</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2010/09/04/ninject-extensions-conventions-ported-to-work-w-wp7.aspx</link><pubDate>Sat, 04 Sep 2010 14:37:55 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:61850</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=61850</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=61850</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2010/09/04/ninject-extensions-conventions-ported-to-work-w-wp7.aspx#comments</comments><description>&lt;p&gt;I have been using Ninject on WP7 now for a few months and I am just now getting around to porting the conventions library (this allows you to NOT have to manually bind all your classes but rather use a convention based approach).&amp;#160; The port of this was pretty simple and can allow you to remove many, many lines of PITA code.&lt;/p&gt;  &lt;p&gt;**** Please note, i have NOT put this through ALL of the paces so it is possible only the simple paths work now ****&lt;/p&gt;  &lt;p&gt;To use the convention based approach all you need to do is use the code below&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;IKernel kernel = new StandardKernel();
kernel.Scan(
    x =&amp;gt;
        {
            x.From( new List {Assembly.GetCallingAssembly(), Assembly.GetExecutingAssembly()} );                    
            x.BindWithDefaultConventions();                    
    } );&lt;/pre&gt;

&lt;p&gt;To get this to work in your project you will need to reference the Ninject.Extensions.Conventions.WP7 assembly.&amp;#160; I have posted the assemblies &lt;a href="https://s3.amazonaws.com/dimecasts.shared/Ninject.Conventions.WP7%2FNinject.Extensions.Conventions.WP7.zip"&gt;here&lt;/a&gt; and the code &lt;a href="https://s3.amazonaws.com/dimecasts.shared/Ninject.Conventions.WP7%2FSource_Ninject.Extensions.Conventions.WP7.zip"&gt;here&lt;/a&gt; (for now, will push to github this week)&lt;/p&gt;

&lt;p&gt;Hope this helps other WP7’ers&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=61850" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/WP7/default.aspx">WP7</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/WindowsPhone/default.aspx">WindowsPhone</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Ninject/default.aspx">Ninject</category></item></channel></rss>