Simple integration sample when using Unity 1.0 Configuration feature in your plain ASP.NET application

May 14, 2008 at 1:50 PM
Edited May 14, 2008 at 1:53 PM

As this (another) simple sample is not really a worth to go to Release folder; I have copy and paste the code over here and removed the sample in the Source Code folder. This simple code give you simple example of how you can start using Unity 1.0 in your ASP.NET application when using the Unity 1.0 configuration feature.

Regards,
Alexander

1. Create the Unity container Interface by copy and paste the below code to IUnityContainer.cs

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.Unity;

namespace UnityASPNET
{
    interface IUnity
    {
            IUnityContainer Container { get; }
    }
}


2. Create ILogger class to this demonstration/testing purposes and copy and paste the following code to ILogger.cs 

//==========================================================================
// Microsoft patterns & practices
// Unity Application Block
//==========================================================================
// Copyright © Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//==========================================================================
namespace Microsoft.Practices.Unity.Tests.TestObjects
{
    // A dummy interface to support testing type mapping
    interface ILogger
    { 
    }
}

 


3. Create WebLogger.cs implementation by using the below code.

//==========================================================================
// Microsoft patterns & practices
// Unity Application Block
//==========================================================================
// Copyright © Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//==========================================================================
namespace Microsoft.Practices.Unity.Tests.TestObjects
{
    // A dummy class to support testing type mapping
    public class WebLogger : ILogger
    {
    }
}
4. Create the ASP.NET Global.cs class (HttpApplication) by using the folloing code:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Tests.TestObjects;

namespace UnityASPNET
{
    public class Global : System.Web.HttpApplication, IUnity
    {
        private static UnityContainer _container;

        public static IUnityContainer Container
        {
            get { return _container; }
        }

        IUnityContainer IUnity.Container
        {
            get { return Container; }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            Initialize();
        } 

        private static void Initialize()
        {
            // create the container at the application initialization phase.
            if (_container == null)
                _container = new UnityContainer();

            // create Unity configuration section
            UnityConfigurationSection section;

            // Get the unity section config from web.config file
            section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
           
            // Apply the configuration to unity container
            section.Containers.Default.Configure(_container);
        }
    }
}


5. Copy and paste the following code to default page (you can skip this if you want to test this in your own pages).

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UnityASPNET._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        A very simple sample with ASP.NET, to see that you get WebLogger resolved from unity container.<br />
        <br />
        &nbsp;<asp:Label ID="Label1" runat="server" ForeColor="Red" Text="This will be updated by page load"
            Width="755px"></asp:Label></div>
    </form>
</body>
</html>
6. Implement the Page_Load method for above Default page by using the below code.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Practices.Unity.Tests.TestObjects;

namespace UnityASPNET
{
    public partial class _Default : System.Web.UI.Page
    {
        /// <summary>
        /// You do here all Unity stuff you need to do before the page is redendered
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            IUnity UnityCtx = Context.ApplicationInstance as IUnity;
           
            // This should find the WebLogger when trying resolve the ILogger
            ILogger logger = UnityCtx.Container.Resolve<ILogger>();
           
            Label1.Text = "Found following ILogger from unity container : "+logger.GetType().FullName.ToString();
        }
       
    }
}


7. Modify your web configuration based on the following code:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity>
    <containers>
      <container>
        <types>
        <type type="Microsoft.Practices.Unity.Tests.TestObjects.ILogger, UnityASPNET"
              mapTo="Microsoft.Practices.Unity.Tests.TestObjects.WebLogger, UnityASPNET" />
        </types>
       </container>
    </containers>
  </unity>
  <connectionStrings/>
    <system.web>
        <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.
        -->
        <compilation debug="true" />
        <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
        <authentication mode="Windows" />
        <!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    </system.web>
</configuration>