Simple integration sample when using Unity 1.0 from plain ASP.NET application.

Developer
May 14, 2008 at 12:32 PM

As this 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. This sample is followed from CanResolveTypeMapping test implemented in Microsoft.Practices.Unity.Tests.UnityContainerFixture.

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();

            // register type
            _container.RegisterType<ILogger, WebLogger>();
        }
    }
}


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();
        }
       
    }
}



 

Coordinator
May 16, 2008 at 3:54 PM
I also have written an article some very basic article on how to utilize Strategy Pattern with Dependency Injection using Unity, again this is not a very big chunk of code but may help a bit of an introduction:

http://www.sidarok.com/web/blog/content/2008/05/15/a-basic-hands-on-introduction-to-unity-di-container.html

We can use this topic to post things that fit to this concept.
Coordinator
May 16, 2008 at 3:55 PM
The source codes for the article : http://www.sidarok.com/files/UnitySample-15052008.zip