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

本文介绍如何在ASP.NET Web应用程序中使用Unity依赖注入容器。包括创建接口文件、实现类及容器配置等步骤,并展示了如何在ASP.NET页面中调用容器获取依赖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的示例演示在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 次.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值