ASP.NET Web Application 中使用 Unity 依赖注入容器

 
下面的示例演示在ASP.NET Web Application 中使用 Unity 依赖注入容器。 下载 ASP.NetWeb Application 源码!!!
 
具体步骤如下:
1. 创建IUnityContainer 接口文件 – IUnity.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.Unity;
namespace UnityASPNET
{
    interface IUnity
    {
            IUnityContainer Container { get; }
    }
}
2. 基于演示的需要,创建ILogger接口 – ILogger.cs
namespace Microsoft.Practices.Unity.Tests.TestObjects
{
    // A dummy interface to support testing type mapping
    interface ILogger
    {
    }
}
3. 创建ILooger接口的实现类 WebLogger.cs
namespace Microsoft.Practices.Unity.Tests.TestObjects
{
    // A dummy class to support testing type mapping
    public class WebLogger : ILogger
    {
    }
}
 
4. 创建 ASP.NET Global.ascx
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; // private
静态成员变量
        public static IUnityContainer Container // public 静态成员变量 Container
        {
            get { return _container; }
        }
        IUnityContainer IUnity.Container // 实现 IUnity 接口,返回 Continer 对象
        {
            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(); //
初始化静态成员变量 _container
            // register type 注册 ILogger 映射
            _container.RegisterType<ILogger, WebLogger>();

        }
    }
}
5. 在ASP.NET 页面调用 IUnityContainer 对象
        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();
 
下载ASP.NET Web Application 源码!!!
 
Source URL:
 
 
 

附件:
UnityASPNETSample_VS2008.rar 148 KB, 下载 178 次.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值