<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tallan&#039;s Technology Blog &#187; Nathaniel Engelsen</title>
	<atom:link href="http://blog.tallan.com/author/nengelsen/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tallan.com</link>
	<description>Tallan&#039;s Top Technologists Share Their Thoughts on Today&#039;s Technology Challenges</description>
	<lastBuildDate>Mon, 06 Feb 2012 02:15:46 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Multi Tenant Architecture via Dependency Injection: Part 3</title>
		<link>http://blog.tallan.com/2010/07/21/multi-tenant-architecture-via-dependency-injection-part-3/</link>
		<comments>http://blog.tallan.com/2010/07/21/multi-tenant-architecture-via-dependency-injection-part-3/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 13:56:01 +0000</pubDate>
		<dc:creator>Nathaniel Engelsen</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=606</guid>
		<description><![CDATA[Using Ninject and Dependency Injection to enhance your ASP.Net MVC application's Multi-Tenant Application.]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/">Part 1</a> we discussed web application Multi Tenant Architecture, and briefly discussed how dependency injection can allow us to manage our client customizations.  In <a href="http://blog.tallan.com/2010/07/16/multi-tenant-architecture-via-dependency-injection-part-2/">Part 2</a>, we explored how to wire up Ninject to our ASP.Net MVC application and begin to use its dependency injection features.</p>
<p>In Part 3 we will look at how to utilize Ninject&#8217;s features within our application, along with what kind of functionality can be delivered.  At this point, let&#8217;s revisit our goals from Part #1:</p>
<ol>
<li>dynamically set which service object(s) we are using to perform our application logic</li>
<li>dynamically set which view we are returning</li>
<li>dynamically set which partial views we are using</li>
</ol>
<p>Hypothetically, let our application be a standard transactional system, with header records at the top level and child records below it. Furthermore, let it be an order entry system, so we will need to know about quantities, prices, have subtotals, etc.  Our standard interface can be for Work Orders, and look something like the following:</p>
<p>WorkOrders.aspx:<br />
<img src="http://blog.tallan.com/wp-content/uploads/2010/07/work-orders.png" alt="Sample Work Orders Screenshot" /><br />
We have some header information (Work Order #, etc.) and child records, and the ability to interact with the application to modify child records and add new ones.  At this point, a large customer likes what you&#8217;ve done so far and wants to use your application to manage their shop.  But instead of work orders, they need to use Purchase Orders.  You need to make some major modifications without affecting your existing functionality, so you create a new page and use Ninject to inject the right functionality into the application.  Because we implemented Goal #2 in Part 2, we merely need to modify our source repository to provide the PurchaseOrders.aspx page instead of WorkOrders.aspx.</p>
<p>From CompanyConfigProvider.cs:</p>
<pre class="brush: csharp;">
                // construct our list of Views to be used throughout the application
                // for Goals #2 and #3
                foreach (KeyValuePair&lt;string, string&gt; item in r.getViews())
                {
                    cc.Views.Add(item.Key, item.Value);
                }
</pre>
<p>In addition, because these Purchase Orders are between your client and their own customers and not intra-company Work Orders, there are potential tax implications &#8212; as such, you will need to introduce a method of keeping track of tax when necessary.  It will utilize the existing Purchase Orders functionality, but will need to augment it &#8212; the perfect usage of partial views.</p>
<p>TotalNoTax.ascx:</p>
<pre class="brush: csharp;">
&lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&quot; %&gt;
&lt;p&gt;Non-Profit Tax Code: &lt;input type=&quot;text&quot; name=&quot;taxinfo&quot; /&gt;&lt;/p&gt;
</pre>
<p>TotalWithTax.ascx:</p>
<pre class="brush: csharp;">
&lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&quot; %&gt;
&lt;p&gt;Tax Amount: &lt;input type=&quot;text&quot; id=&quot;taxinfo&quot; name=&quot;taxinfo&quot; /&gt;&lt;/p&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    function updateTax() {
        var qty = parseFloat($(&quot;#quantity&quot;).val());
        $(&quot;#taxinfo&quot;).val(qty * 150 * .06);
    }

    $(document).ready(function() {
        $(&quot;#quantity&quot;).blur(updateTax);
        $(&quot;#itemType&quot;).change(updateTax);
    });
&lt;/script&gt;
</pre>
<p>Very simply, we will use jQuery to manage a new form element that will include tax when necessary.  Let&#8217;s start putting it all together.  First, let&#8217;s take a look at our controller:</p>
<p>From OrdersController.cs:</p>
<pre class="brush: csharp;">
using {etc}

namespace MultiTenantNinject.Controllers
{
    [HandleError]
    [ProvideCompanyConfig]
    public class OrdersController : Controller
    {
</pre>
<p>As you can see, we inherit from Controller like normal and utilize our ProvideCompanyConfig attribute so that we can be assured we have access to our company config upon rendering.  Let&#8217;s take a look at an Action:</p>
<pre class="brush: csharp;">
        public ActionResult Index()
        {
            ViewResult v = View(_companyConfig.Views[&quot;Order Management&quot;]);

			// add view data items for the header and children;

			// add item to be used for determining if it's a taxable or non-taxable transaction:
			v.ViewData.add(&quot;taxState&quot;,repository.TaxState);

            return v;

        }
</pre>
<p>The first step in rendering the View to the user is ensuring we have an &#8220;Order Management&#8221; entry in our Views collection that establishes what type of major functionality to use.  Our repository would load the config file with a text entry like &#8220;WorkOrders&#8221; or &#8220;PurchaseOrders&#8221; to correspond with &#8220;WorkOrders.aspx&#8221; or &#8220;PurchaseOrders.aspx&#8221;, respectively.  We can set our ViewData at this point, perhaps using a service object (which we will explore soon) and then return the view.  At this point, we have a solid understanding of achieving Goal #2, so let&#8217;s take a look at the few lines necessary to achieve Goal #3:</p>
<p>From PurchaseOrders.aspx:</p>
<pre class="brush: csharp;">
    &lt;% var configSettings = (MultiTenantNinject.Models.ICompanyConfig)ViewData[&quot;companyConfigSettings&quot;];  %&gt;
	&lt;h3&gt;Purchase Orders&lt;/h3&gt;
	... etc ...
    &lt;p&gt;&lt;% Html.RenderPartial(configSettings.Views[string.Format(&quot;Taxes_{0}&quot;,ViewData[&quot;taxState&quot;])]); %&gt;
</pre>
<p>By utilzing the correct entry in our repository for the user&#8217;s state, we can provide the correct tax functionality.  If the company&#8217;s location was in Florida, the repository could provide &#8220;TotalWithTax&#8221; for the &#8220;Taxes_FL&#8221; binding, and &#8220;TotalNoTax&#8221; for the other states.  Obviously we can take it up a level of abstraction and determine whether or not this transaction is taxable in the controller or service object, but this serves as an adequate example of Goal #3.  Lastly, let&#8217;s take a look at our solution for Goal #1 &#8212; it&#8217;s all well and good when we can provide custom front-end functionality for our users, but at some point we will need to implement logic and manipulate data.  Let&#8217;s revisit the module where we inject our services:</p>
<p>From OrderModule.cs:</p>
<pre class="brush: csharp;">
        public override void Load()
        {
            // use reflection to bind a list of types (from our Config's &quot;Bindings&quot; collection)
            // to be used when called upon during injection
            string serviceLocationPrefix = &quot;MultiTenantNinject.Services.&quot;;
            foreach (KeyValuePair&lt;string,string&gt; item in _config.Bindings)
            {
                Bind(Type.GetType(serviceLocationPrefix + item.Key)).To(Type.GetType(serviceLocationPrefix + item.Value));
            }
        }
</pre>
<p>We will need to provide an interface and an implementation for our service(s).  Firstly, the interface:</p>
<pre class="brush: csharp;">
IOrderService.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web.Mvc;

namespace MultiTenantNinject.Services
{
    public interface IOrderService
    {
        string Process(ViewDataDictionary viewdata);
        DataTable Orders { get; set; }
    }
}
</pre>
<p>and one of the implementations:</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Mvc;

namespace MultiTenantNinject.Services
{
    public class VideoCardOrderService: IOrderService
    {

        #region IService Members

        public string Process(ViewDataDictionary viewdata)
        {
            // here we do transactions pertaining to video cards
            return &quot;Thanks for buying a video card!&quot;;
        }

        #region Orders
        private DataTable _Orders;
        public DataTable Orders
        {
            get
            {
                return _Orders;
            }
            set
            {
                if (_Orders == value) return;
                _Orders = value;
            }
        }
        #endregion

        #endregion

    }
}
</pre>
<p>Service objects can perform most of the functionality of your application, and do not need to be gone over in great detail, as they are as varied as anything else can be.  Suffice it to say that it&#8217;s a standard interface/implementation pattern of development.  Ninject allows you to set it up for injection, as we did in Part 2, so that whenever you call a particular interface for this user a particular implementation is used.  &#8220;VideoCardOrderService&#8221; could easily be &#8220;MotherboardOrderService&#8221; or &#8220;CarOrderService&#8221;:</p>
<p>From OrdersController.cs:</p>
<pre class="brush: csharp;">
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save()
        {
            _orderService.Process(ViewData);
            return new RedirectResult(&quot;Index&quot;);
        }
</pre>
<p>Our controller, in the end, is completely agnostic of our major functionality, our minor (partial view) functionality, and our domain logic:</p>
<p>OrdersController.cs:</p>
<pre class="brush: csharp;">
using {etc}
using Ninject;

namespace MultiTenantNinject.Controllers
{
    [HandleError]
    [ProvideCompanyConfig]
    public class OrdersController : Controller
    {
        ICompanyConfig _companyConfig;
        IOrderService _orderService;

        public OrdersController(ICompanyConfig pCompanyConfig, IOrderService pOrderService)
        {
            _companyConfig = pCompanyConfig;
            _orderService = pOrderService;
        }

        public OrdersController()
        {
        }

        public ActionResult Index()
        {
            ViewResult v = View(_companyConfig.Views[&quot;Order Management&quot;]);

			// add view data items for the header and children;

			// add item to be used for determining if it's a taxable or non-taxable transaction:
			v.ViewData.add(&quot;taxState&quot;,repository.TaxState);

            return v;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save()
        {
            _orderService.Process(ViewData);
            return new RedirectResult(&quot;Index&quot;);
        }
    }
}
</pre>
<p>Thus, the conclusion to our series about utilizing dependency injection within ASP.Net MVC to enhance a Multi-Tenant Architecture.  We can provide service objects without our controller (or anything else) performing logic switches, we can provide major changes to functionality without creating a new codebase, and we can provide in-place customizations truly in-place.  In addition, we&#8217;ve created our application such that we can utilize any kind of data layer or repository and we can utilize testing frameworks to test our code without having to rewrite anything.  And lastly, although it&#8217;s taken a moderate level of effort to get to this point, we can be secure in the knowledge that additional changes can be implemented without affecting existing functionality, and we can easily swap out functionality when the situation arises with very little additional effort.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/07/21/multi-tenant-architecture-via-dependency-injection-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multi Tenant Architecture via Dependency Injection: Part 2</title>
		<link>http://blog.tallan.com/2010/07/16/multi-tenant-architecture-via-dependency-injection-part-2/</link>
		<comments>http://blog.tallan.com/2010/07/16/multi-tenant-architecture-via-dependency-injection-part-2/#comments</comments>
		<pubDate>Fri, 16 Jul 2010 12:37:17 +0000</pubDate>
		<dc:creator>Nathaniel Engelsen</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=570</guid>
		<description><![CDATA[Using Ninject and Dependency Injection to enhance your ASP.Net MVC application's Multi-Tenant Application.]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/">Part 1</a> we discussed Multi Tenant Architecture as it pertains to web development, along with how dependency injection (specifically with Ninject) can allow us to manage our necessary customizations a bit cleaner.</p>
<p>To start off with, let&#8217;s talk about using Ninject with ASP.Net MVC.  You&#8217;ll need to download the appropriate Ninject version for your .NET framework.  Our example will use Ninject 2.0 with ASP.Net MVC 1.  Download Ninject from the homepage at <a href="http://ninject.org/">http://ninject.org/</a> and visit the <a href="http://ninject.org/learn">dojo</a> and <a href="http://wiki.github.com/ninject/ninject/">github</a> to learn the basics. Ninject will manage our controllers for us (it needs to, so it can monitor for injection points) and so will need to be tightly integrated into our application.  For starters, we&#8217;re going to need to change our global.asax.cs file.  Take a look:</p>
<p>Global.asax.cs:</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject.Web.Mvc;
using Ninject;
using Ninject.Modules;
using MultiTenantNinject.Controllers.Components;
using MultiTenantNinject.Models;

namespace MultiTenantNinject
{
  // Inherit from NinjectHttpApplication instead of HttpApplication
  public class MvcApplication : NinjectHttpApplication
  {
    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute(&quot;{resource}.axd/{*pathInfo}&quot;);

      // hack for visual studio's web server
      routes.IgnoreRoute(&quot;{*favicon}&quot;, new { favicon = @&quot;(.*/)?favicon.ico(/.*)?&quot; });

      routes.MapRoute(
        &quot;Default&quot;, // Route name
        &quot;{controller}/{action}/{id}&quot;, // URL with parameters
        new { controller = &quot;Home&quot;, action = &quot;Index&quot;, id = &quot;&quot; } // Parameter defaults
      );

    }

    // we use OnApplicationStarted, because Ninject is using Application_Started
    protected override void OnApplicationStarted()
    {
      // no big surprise here -- register our routes.
      RegisterRoutes(RouteTable.Routes);
      // register every controller in our application for injection
      RegisterAllControllersIn(Assembly.GetExecutingAssembly());
    }

    // this is called automatically from within the Ninject framework
    protected override IKernel CreateKernel()
    {
      // create a Kernel to manage injections.
      // have the Kernel process our &quot;SetupModule&quot; class
      IKernel k = new StandardKernel(new SetupModule());
      // have the Kernel process our &quot;ConfigModule&quot; class
      k.Load(new ConfigModule());
      // have the Kernel process our &quot;OrderModule class
      // pass an instance of our company config that our ConfigModule calls for
      k.Load(new OrderModule(k.Get&lt;ICompanyConfig&gt;()));
      return k;
    }
  }
}
</pre>
<p>You can see how the CreateKernel() method loads a number of Modules to manage our Dependency Injection.  Let&#8217;s take a look at these modules. The first module to investigate will provide bindings for our .NET MVC dependencies.</p>
<p>SetupModule.cs:</p>
<pre class="brush: csharp;">
using {etc}
using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;

namespace MultiTenantNinject.Controllers.Components
{
    // inherit from NinjectModule
    public class SetupModule : NinjectModule
    {
        // NinjectModule is an implementation of the Strategy design pattern and must implement &quot;Load()&quot;
        public override void Load()
        {
            // Let's inject .NET MVC framework dependencies, wow!
            Bind&lt;IFormsAuthentication&gt;()
                .To&lt;FormsAuthenticationService&gt;();
            Bind&lt;IMembershipService&gt;()
                .To&lt;AccountMembershipService&gt;();
            Bind&lt;MembershipProvider&gt;()
                .ToMethod(ctx =&gt; Membership.Provider);
        }
    }
}
</pre>
<p>Our next module will bind the heart of our Multi Tenant Architecture, the &#8220;Company Config&#8221;. This configuration object will be lightweight, cached server-side (ideally once for each company) and will be available during most operations of the page lifecycle.</p>
<p>ICompanyConfig.cs:</p>
<pre class="brush: csharp;">
using {etc}

namespace MultiTenantNinject.Models
{
    public interface ICompanyConfig
    {
        // Task #1 -- provide service objects
        Dictionary&lt;string, string&gt; Bindings { get; set; }
        // Task #2 &amp; #3 -- provide views and partial views
        Dictionary&lt;string, string&gt; Views { get; set; }

        String CompanyName { get; set; }

    }
}
</pre>
<p>ConfigModule.cs:</p>
<pre class="brush: csharp;">
using {etc}

namespace MultiTenantNinject.Controllers.Components
{
    public class ConfigModule : NinjectModule
    {
        public override void Load()
        {
            // Ninject.Activation.Provider is a factory object.
            CompanyConfigProvider Provider = new CompanyConfigProvider(WebConfigurationManager.AppSettings);

            // Bind our service (ICompanyConfig) to its implementation using the
            // aforementioned Provider.  Bind it so that each request uses the same
            // instance of the service.
            Bind&lt;ICompanyConfig&gt;()
                .ToProvider(Provider)
                .InRequestScope();

        }
    }
}
</pre>
<p>Our next module will control the functionality for our example customizations revolving around Purchase Orders.  In practice we could have multiple modules, perhaps one for each functional area of our application, but our single module will serve our purposes here:</p>
<p>OrderModule.cs:</p>
<pre class="brush: csharp;">
using {etc}

namespace MultiTenantNinject.Controllers.Components
{
    public class OrderModule : NinjectModule
    {
        private readonly ICompanyConfig _config;

        // We see our first &quot;Inject&quot; attribute.
        // Here we will take an instance of our company config
        // and later use it to bind our application services
        [Inject]
        public OrderModule(ICompanyConfig companyConfig)
        {
            _config = companyConfig;
        }

        public override void Load()
        {
            // use reflection to bind a list of types (from our Config's &quot;Bindings&quot; collection)
            // to be used when called upon during injection
            string serviceLocationPrefix = &quot;MultiTenantNinject.Services.&quot;;
            foreach (KeyValuePair&lt;string,string&gt; item in _config.Bindings)
            {
                Bind(Type.GetType(serviceLocationPrefix + item.Key)).To(Type.GetType(serviceLocationPrefix + item.Value));
            }
        }
    }
}
</pre>
<p>Let&#8217;s briefly revisit our goals from Part #1:</p>
<ol>
<li>dynamically set which service object(s) we are using to perform our application logic</li>
<li>dynamically set which view we are returning</li>
<li>dynamically set which partial views we are using</li>
</ol>
<p>At this point we can see the pattern unfolding.  We use our Modules to dictate to the Kernel what strategies to use when binding implementations to our services.  We can use reflection, we can use strings and types, and we can use Providers inside of our Modules during binding.  We will be coming back to OrderModule.cs, as that is part of our implementation for Goal #1.  Let us take a look now at our Provider from our ConfigModule:</p>
<p>CompanyConfigProvider.cs:</p>
<pre class="brush: csharp;">
using {etc}
using Ninject.Activation;

namespace MultiTenantNinject.Models
{
    // inherit from Ninject.Activation.Provider
    public class CompanyConfigProvider: Provider&lt;CompanyConfig&gt;
    {
        // these settings are provided by our web.config in this example
        public CompanyConfigProvider(NameValueCollection settings)
        {
            Settings = settings;
        }

        protected NameValueCollection Settings { get; set; }

        // build and return an instance of our CompanyConfig using the specific context
        // IProvider is a Factory that will have its CreateInstance() method called
        // the first time that a CompanyConfig is injected
        protected override CompanyConfig CreateInstance(IContext context)
        {
            // use a caching mechanism to store our company config.  we cannot
            // cache in the Application cache because we have a Multi Tenant Application.
            // we can use Session in a pinch, although depending on your application's traffic,
            // you might need to use something else
            System.Web.SessionState.HttpSessionState Session = HttpContext.Current.Session;
            CompanyConfig cc = null;

            // if we don't have a cached company config:
            if (Session == null || Session[&quot;cc&quot;] == null)
            {
                cc = new CompanyConfig();
                // our repository is extremely unsophisticated, but you should
                // get the idea of how this works.  it may very well be passed in
                // via constructor injection
                MultiTenantNinject.Models.Repository r = new Repository();

                // construct our list of Views to be used throughout the application
                // for Goals #2 and #3
                foreach (KeyValuePair&lt;string, string&gt; item in r.getViews())
                {
                    cc.Views.Add(item.Key, item.Value);
                }
                // construct our list of service bindings to be used throughout the application
                // for Goal #1 (previously seen in OrderModule.cs
                foreach (KeyValuePair&lt;string, string&gt; item in r.getBindings())
                {
                    cc.Bindings.Add(item.Key, item.Value);
                }
                // if we can cache our company config:
                if (Session != null &amp;&amp; Session[&quot;cc&quot;] == null)
                {
                    Session[&quot;cc&quot;] = cc;
                }
                // set company name (normally would be from the repository)
                cc.CompanyName = &quot;Widgets, Inc.&quot;;
            }
            else  // we have a previously cached company config
            {
                cc = (CompanyConfig)Session[&quot;cc&quot;];
            }

            return cc;
        }
    }
}
</pre>
<p>To make our lives a little easier and yet more structured, let&#8217;s create an ActionFilterAttribute to inject our CompanyConfig into our Views:</p>
<p>From ProvideCompanyConfigAttribute:</p>
<pre class="brush: csharp;">
    public class ProvideCompanyConfigAttribute : ActionFilterAttribute
    {
        [Inject]
        public ICompanyConfig Settings { get; set; }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewData.Add(&quot;companyConfigSettings&quot;, Settings);
        }
    }
</pre>
<p>We use Ninject&#8217;s &#8220;Inject&#8221; attribute to provide the CompanyConfig to our Attribute, and then inject the config into the controller as a matter of course.</p>
<p>At this point we&#8217;ve seen how Ninject positions itself within our application (a controller factory and application superclass) and how we can use Ninject&#8217;s modularity to manage our bindings.  We&#8217;ve touched upon Goals #1, 2, and 3, and can see it taking shape before us.  We have a company configuration that encapsulates the customizations for the currently logged in user and provides the customized bindings and views for that logged in user.  We have basically everything we need to begin working with our customized functionality.</p>
<p>To get this far we have made the following assumptions:</p>
<ol>
<li>Your repository works.</li>
<li>You have an ASP.Net MVC application in otherwise working order.</li>
<li>You have downloaded and referenced the Ninject libraries.</li>
</ol>
<p>In Part 3 we will look at our application controllers and views, and then explore what we can do to provide customized functionality to our users.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/07/16/multi-tenant-architecture-via-dependency-injection-part-2/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Multi Tenant Architecture via Dependency Injection: Part 1</title>
		<link>http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/</link>
		<comments>http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 20:51:34 +0000</pubDate>
		<dc:creator>Nathaniel Engelsen</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Enterprise .NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://blog.tallan.com/?p=421</guid>
		<description><![CDATA[Discover how to use Inversion of Control and Dependency Injection to enhance your web application's Multi-Tenant Application.]]></description>
			<content:encoded><![CDATA[<p>Chances are, if you&#8217;ve been developing web applications for a number of years, you&#8217;ve noticed a few ways of provisioning your application for your users.</p>
<ol>
<li>Your users all log into a single codebase.  It might be load balanced, cached, the whole nine yards, but everybody is on the same build and accesses the same data.</li>
<li>Your users log into multiple codebases and/or multiple databases.  Perhaps you have some high-powered customers who want custom functionality, and so you forked your codebase and created them their own functionality.   Most likely, you can update your customer&#8217;s builds independently of one another.</li>
<li>Your users all log into a single codebase, but you use flags, connection strings, config files, etc., to logically separate out your users from one another.  Your high-powered customers see their custom functionality, but it&#8217;s part of the main codebase and you are able to update your application in one fell swoop.</li>
</ol>
<p>We&#8217;re going to talk more about option #3 &#8212; the Multi-Tenant Architecture.  There is <a href="http://lmgtfy.com/?q=multi+tenant+architecture">PLENTY of reading material</a> out there for you to learn more about multi-tenancy.  Suffice it to say that it allows you to satisfy multiple sets of requirements for your multiple customers via one codebase, and your customers, most likely, are logically separate in the database(i.e. they use one schema and one top-level data store) instead of physically separate.</p>
<p>In the past, (and present, for novice developers), it was a usual practice to utililze config files, database flags, etc., to turn on and off functionality. Your code may have looked something like:</p>
<pre class="brush: csharp;">
&lt;% if (showThisFunctionality) %&gt;
&lt;-- this widget is shown --&gt;;
&lt;% else %&gt;;
&lt;-- this other widget is shown --&gt;
&lt;% end if %&gt;
</pre>
<p><strong>Fig 1: Classic ASP</strong></code></p>
<p>By utilizing a dependency injection framework you can provide features to your users, based on configuration and setup, without having to use logic switches inside of your application.  This is above and beyond the existing benefits of using a dependency injection framework, which is not the scope of this essay but can be enumerated <a href="http://misko.hevery.com/2009/01/14/when-to-use-dependency-injection/">here</a>, for instance.  Our example will use <a href="http://ninject.org/">Ninject</a> and ASP.NET MVC, although you could use any DI and application frameworks.</p>
<p>Our challenge for this example will be to:</p>
<ol>
<li>dynamically set which service object(s) we are using to perform our application logic</li>
<li>dynamically set which view we are returning</li>
<li>dynamically set which partial views we are using</li>
</ol>
<p>Our example will utilize dependency injection to provide order fulfillment functionality for our customers.  For goal #1, we will use Ninject's MVC integration to provide service objects for our controllers.  Once Ninject is wired up, we can have our service objects perform our application logic against our Model, and as a matter of fact, Behavioral design patterns are a good fit here.  Goal #2 is achievable fairly easily with ASP.Net MVC.  Setting which view you're returning via any MVC framework is often a very simple operation and comes down to returning a string variable which represents the view in question.  For ASP.NET MVC we can '<code><span style="color: #0000ff">return</span><span>View(</span><span style="color: #a31515">"viewName"</span><span>)'</span></code> where "viewName" is the name of the view we wish to return.  There is also the obvious <code>"<span style="color: #0000ff">return </span><span>View(viewNameVariable)</span>"</code> override.  Our example will use a configuration object to set which view is being called.  Accomplishing goal #3 can be thought of as an extension of #2, but "finer grained". Where you have general and reusable functionality within your view, your partial views allow you to have specific customizations exposed to your user in a consistent fashion.</p>
<p>In Part 2 we will investigate both integrating Ninject with ASP.Net MVC as well as what shape our framework will take.  In Part 3 we will finish up our framework architecture and explore how to use it to provide features to our users.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tallan.com/2010/07/11/multi-tenant-architecture-via-dependency-injection-part-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

