Unity 简单示例代码和向导/Unity Aplication Block

 

Unity 简单示例代码和向导

关于Unity 的说明和下载地址,请访问[微软控制反转和依赖注入容器Unity 1.0发布] http://forum.entlib.com/Default.aspx?g=posts&t=25

下面的范例主要实现:首先,定义ILogger 接口。然后,定义一个实现该接口的具体类 ConsoleLogger。其次,定义一个业务类 CustomerTasks,通过constructor 函数注入ILogger 依赖类,并在CustomerTasks 的其中一个方法内调用 ILogger Log方法。

1. 定义ILogger 接口。

namespace  UnitySamples
{
    
public   interface  ILogger
    {
        
void  Log( string  message);
    }
}

2. 定义ConsoleLogger类,实现ILogger 接口。

namespace  UnitySamples
{
    
public   class  ConsoleLogger : ILogger
    {
        
public  ConsoleLogger()
        {
            Console.WriteLine(
" Hello from constructor " );
        }

        
public   void  Log( string  message)
        {
            Console.WriteLine(message);
        }
    }
}


3. 定义业务类CustomerTasks

namespace  UnitySamples
{
    
// create a class that takes an ILogger through constructor injection.
     public   class  CustomerTasks
    {
        
private   readonly  ILogger logger;

        
public  CustomerTasks(ILogger logger)
        {
            
this .logger  =  logger;
        }

        
public   void  SaveCustomer()
        {
            logger.Log(
" Saved customer " );
        }
    }
}

创建CustomerTasks类,该类通过constructor 函数注入ILogger依赖类。

4. 使用UnityContainer 依赖注入容器。

using  Microsoft.Practices.Unity;

namespace  UnitySamples
{
    
public   partial   class  Form1 : Form
    {
        
public  Form1()
        {
            InitializeComponent();
        }

        
private   void  button1_Click( object  sender, EventArgs e)
        {
            UnityContainer container 
=   new  UnityContainer();
            container.RegisterType
< ILogger, ConsoleLogger > ( new  ContainerControlledLifetimeManager());

            CustomerTasks tasks1 
=  container.Resolve < CustomerTasks > ();
            CustomerTasks tasks2 
=  container.Resolve < CustomerTasks > ();
            tasks1.SaveCustomer();
            tasks2.SaveCustomer();    
        }
    }
}

通过RegisterType 方法注册ILogger Singleton 实例。然后调用UnityContainerResolve方法,并指定类型实例为 CustomerTasks。由于前面并没有注册该类,UnityContainer 将负责生成一个CustomerTasks 的实例并返回。因为CustomerTasks 类中声明了custructor函数注入ILogger 接口,UnityContainer 将使用先前注册的ILogger 类型,自动实例化ConsoleLogger对象。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值