[转载]利用Attribute简化Unity框架IOC注入

[转载]利用Attribute简化Unity框架IOC注入 – 破狼 – 博客园.

View Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Green.Utils;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

ELUnityUtility.Resolve<IClass2>().Show();
(typeof(IClass2).Resolve() as IClass2).Show();
Console.Read();
}
}

public interface IClass1
{
void Show();
}

[Green.Utils.ELPolicyinjection]
public class Class1 : IClass1
{

#region IClass1 成员
[TestCallHandler]
public void Show()
{
Console.WriteLine(this.GetType());
}

#endregion
}

[Green.Utils.UnityInjection(First, Name = class2, ConfigFile = App1.config)]
public interface IClass2
{
void Show();
}

[Green.Utils.ELPolicyinjection]
public class Class2 : ConsoleApplication1.IClass2
{
[Microsoft.Practices.Unity.Dependency(class1)]
public IClass1 Class1
{
get;
set;
}

[TestCallHandler]
public void Show()
{
Console.WriteLine(this.GetType());
Class1.Show();
}
}

[Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationElementType(typeof(CustomCallHandlerData))]
public class TestCallHandler : ICallHandler
{
#region ICallHandler 成员

public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
if (input == nullthrow new ArgumentNullException(input);
if (getNext == nullthrow new ArgumentNullException(getNext);
Console.WriteLine(begin….);
var result = getNext()(input, getNext);
Console.WriteLine(end….);
return result;
}

public int Order
{
get;
set;
}

#endregion
}

[AttributeUsage(AttributeTargets.Method)]
public class TestCallHandlerAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
{
return new TestCallHandler();
}
}
}

欢迎大家指正,批评,交流是的大家都功能进步。代码下载

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏