Unity在WPF中的应用
1. 本文的实现类继承于IRepository
using System;
using System.Linq;
using System.Linq.Expressions;
using Zhang.Test.ELUnityUtility; namespace Zhang.Test.IDataLayer
{
[UnityInjection("First", Name = "GenericRepository", ConfigFile = "Zhang.Test.exe.config")]
public interface IRepository
{
IQueryable<T> GetEntitiesByCondition<T>(Expression<Func<T, bool>> predicate = null) where T : class;
T GetEntityByCondition<T>(Expression<Func<T, bool>> predicate) where T : class;
T GetEntityByPK<T>(object key) where T : class;
IQueryable<T> GetEntitiesBySqlCommond<T>(String sqlCommond);
void Insert<T>(T entity) where T : class;
//void BatchInsert<T>(IEnumerable<T> entities);
void Update<T>(T entity) where T : class;
void Delete<T>(T entity) where T : class;
//void BatchDelete<T>(IEnumerable<T> entities);
int SaveChanges();
}
}
2. 实现效果
通过调用接口的实现类可以实现调用其中的方法,如下:
class Repository:IRepository
{
public Insert<T>(T entity) where T: class
{
Console.WriteLine("Insert method");
}
........
}
3. 通过实例化Repository就可以调用其中的方法,但是AOP的作用是向在调用方法之前或之后注入其他代码,使它可以在不动Repository的基础上重用它。
4. 调用处理方法
我们先定义一段处理方法的代码,Unity规定它是ICallHandler的一个实现:
using System;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension; namespace Zhang.Test.DataLayer
{
[ConfigurationElementType(typeof (CustomCallHandlerData))]
public class CallHandler : ICallHandler
{
#region ICallHandler 成员 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
if (input == null) throw new ArgumentNullException("input");
if (getNext == null) throw new ArgumentNullException("getNext");
//Console.WriteLine("begin....");
var result = getNext()(input, getNext);
//Console.WriteLine("end....");
return result;
} public int Order { get; set; } #endregion
} }
5. OK, 下面我们怎么把CallHandler和IRepository关联起来,大体有两种方法:
- 通过代码直接关联,这种方法比较直接,首先,先建一个Attribute:
[AttributeUsage(AttributeTargets.Method)]
public class CallHandlerAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new CallHandler();
}
}
然后在IRepository的实现中使用如下代码:
[CallHandler]
class OutputImplement1 : IRepository
{
int SaveChanges()
}
这里靠此Attribute就将二者关联了起来
现在执行处写:
var container1 = new UnityContainer()
.AddNewExtension<Interception>()
.RegisterType<IOutput, OutputImplement1>();//声明UnityContainer并注册IOutput
container1
.Configure<Interception>()
.SetInterceptorFor<IOutput>(new InterfaceInterceptor());
var op1 = container1.Resolve<IOutput>();
op1.SaveChanges();//调用
- 用配置文件处理
如果用配置文件的话就不需要使用Attribute了,所以实现的类如下:
class OutputImplement2 : IRepository
{
int SaveChanges()
}
这里我们不需要属性来标记了,而使用配置文件,我们建一个Unity.xml的配置文件,
<!--Unity configuration begin-->
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration ">
</sectionExtension>
<!--<assembly name="Zhang.Test.DataLayer" />
<assembly name="Zhang.Test.IDataLayer" />-->
<container name="First">
<extension type="Interception" />
<!--<register type="Zhang.Test.IDataLayer.ISample`1,Zhang.Test.IDataLayer"
mapTo="Zhang.Test.DataLayer.SampleIocDAL,Zhang.Test.DataLayer" name="ISample">
<interceptor type="InterfaceInterceptor" />
<policyInjection />
</register>-->
<register type="Zhang.Test.IDataLayer.IRepository,Zhang.Test.IDataLayer"
mapTo="Zhang.Test.DataLayer.GenericRepository,Zhang.Test.DataLayer" name="GenericRepository">
</register>
<!--<interceptors>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
<parameters>
<parameter value="C:\Temp\LogOutput.txt"/>
</parameters>
</interceptor>
</interceptors>-->
</container> </unity>
最后我们来执行一下,要比第一种复杂一点:
using System;
using System.Linq;
using System.Linq.Expressions;
using Zhang.Test.ELUnityUtility;
using Zhang.Test.IDataLayer;
using Zhang.Test.Common;
using System.Collections.Generic;
using Zhang.Test.DataExchange;
using Zhang.Test.DataTransferObject; namespace Zhang.Test.BusinessLayer
{
public class BaseBL
{
private readonly IRepository repository; public BaseBL()
{
string startTime = LoggerHelper.StartEvent("constructor"); try
{
//Initialize repository class by Unity
repository = typeof (IRepository).Resolve<IRepository>() as IRepository;
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw e;
}
finally
{
LoggerHelper.EndEvent(startTime);
}
} public IQueryable<T> QueryEntitiesByCondition<T>(Expression<Func<T, bool>> predicate = null) where T : class
{
string startTime = LoggerHelper.StartEvent(); IQueryable<T> result = null;
try
{
if (null != repository)
{
result = repository.GetEntitiesByCondition(predicate);
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
} return result;
} /// <summary>
/// Query first entity by filter
/// </summary>
/// <param name="predicate">Lamda expression</param>
/// <returns>Entity</returns>
public T QueryEntityByCondition<T>(Expression<Func<T, bool>> predicate) where T : class
{
string startTime = LoggerHelper.StartEvent(); T reslult = null;
try
{
if (null != repository && null != predicate)
{
reslult = repository.GetEntityByCondition(predicate);
}
}
catch (Exception e) //
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
} return reslult;
} /// <summary>
/// Query a entity by primary key
/// </summary>
/// <param name="key">primary key of entity</param>
/// <returns>Entity</returns>
public T QueryEntityByPK<T>(object key) where T : class
{
string startTime = LoggerHelper.StartEvent(); T reslult = null;
try
{
if (null != repository && null != key)
{
reslult = repository.GetEntityByPK<T>(key);
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
} return reslult;
} /// <summary>
/// Query entity set by sqlcommond, property of entity should be match with sqlcommond
/// </summary>
/// <param name="sqlCommond">SQL</param>
/// <returns>Entity set</returns>
public IQueryable<T> QueryEntitiesBySqlCommond<T>(String sqlCommond)
{
string startTime = LoggerHelper.StartEvent(); IQueryable<T> result = null;
try
{
Dictionary<string, Object> msg = new Dictionary<string, object>();
msg.Add("QueryEntitiesBySqlCommond", sqlCommond);
LoggerHelper.Info(msg);
if (null != repository && !string.IsNullOrEmpty(sqlCommond))
{
result = repository.GetEntitiesBySqlCommond<T>(sqlCommond);
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
} return result;
} /// <summary>
/// Query entity set by sqlcommond, property of entity should be match with sqlcommond
/// </summary>
/// <param name="sqlCommond">SQL</param>
/// <returns>Entity set</returns>
public string QueryValueBySqlCommond(String sqlCommond)
{
string startTime = LoggerHelper.StartEvent(); //IQueryable<string> result = null;
try
{
Dictionary<string, Object> msg = new Dictionary<string, object>();
msg.Add("QueryValueBySqlCommond", sqlCommond);
LoggerHelper.Info(msg); if (null != repository && !string.IsNullOrEmpty(sqlCommond))
{
return QueryEntitiesBySqlCommond<string>(sqlCommond).FirstOrDefault();
/*result = QueryEntitiesBySqlCommond<string>(sqlCommond);
if (result != null && result.ToList().Count > 0)
{
return result.ToList()[0];
}*/
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
} return "";
} /// <summary>
/// Query by sqlcommond, property of entity should be match with sqlcommond
/// </summary>
/// <param name="sqlCommond">SQL</param>
/// <returns>num</returns>
public int QueryIntValueBySqlCommond(String sqlCommond)
{
string startTime = LoggerHelper.StartEvent(); //IQueryable<int?> result = null;
try
{
Dictionary<string, Object> msg = new Dictionary<string, object>();
msg.Add("QueryIntValueBySqlCommond", sqlCommond);
LoggerHelper.Info(msg); if (null != repository && !string.IsNullOrEmpty(sqlCommond))
{
int? result = QueryEntitiesBySqlCommond<int?>(sqlCommond).FirstOrDefault();
if (result != null)
{
return Convert.ToInt32(result);
}
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
} return -;
} /// <summary>
/// Create entity
/// </summary>
/// <param name="entity">entity</param>
public void CreateEntity<T>(T entity) where T : class
{
string startTime = LoggerHelper.StartEvent(); try
{
if (null != repository && null != entity)
{
repository.Insert(entity);
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
}
} /// <summary>
/// Modify entity
/// </summary>
/// <param name="entity">entity</param>
public void ModifyEntity<T>(T entity) where T : class
{
string startTime = LoggerHelper.StartEvent(); try
{
if (null != repository && null != entity)
{
repository.Update(entity);
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
}
} /// <summary>
/// Remove entity
/// </summary>
/// <param name="entity">entity</param>
public void RemoveEntity<T>(T entity) where T : class
{
string startTime = LoggerHelper.StartEvent(); try
{
if (null != repository && null != entity)
{
repository.Delete(entity);
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
}
} /// <summary>
/// commit transaction
/// </summary>
/// <returns>Number of objects to be saved</returns>
public int SaveChanges()
{
string startTime = LoggerHelper.StartEvent(); var nums = ;
try
{
if (null != repository)
{
nums = repository.SaveChanges();
}
}
catch (Exception e)
{
LoggerHelper.Error(e);
throw;
}
finally
{
LoggerHelper.EndEvent(startTime);
} return nums;
} public string ImportSuccess()
{
return ResourceHelper.GetRsByKey("Common_Result_ImprotEntitySuccessfully");
}
public string ImportUnSuccess()
{
return ResourceHelper.GetRsByKey("Common_Result_ImprotEntityUnsuccessfully");
}
public ExecutionResult CreateExecutionResult(string rowIndex,string message)
{
ExecutionResult er = new ExecutionResult();
er.RowIndex = rowIndex;
er.Message = message;
return er;
} }
}
附加Unity的代码:
1. using System;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration; namespace Zhang.Test.ELUnityUtility
{
public static class ELUnityUtility
{
public static T Resolve<T>() where T : class
{
return Resolve<T>(typeof (T)) as T;
} public static object Resolve<T>(this Type type)
{
var attrs = type.GetCustomAttributes(typeof (UnityInjectionAttribute), true) as UnityInjectionAttribute[];
if (attrs != null && attrs.Length > 0)
{
var attr = attrs[0];
var unitySection = attr.GetUnityConfigurationSection();
if (unitySection != null)
{
var container = new UnityContainer().LoadConfiguration(unitySection,
string.IsNullOrEmpty(attr.Container) ? unitySection.Containers.Default.Name : attr.Container);
var obj = string.IsNullOrEmpty(attr.Name)
? container.Resolve(type)
: container.Resolve(type, attr.Name);
if (obj != null)
{
var piabAtttr =
obj.GetType().GetCustomAttributes(typeof (ELPolicyinjectionAttribute), false) as
ELPolicyinjectionAttribute[];
if (piabAtttr.Length > 0)
{
obj = PolicyInjection.Wrap(type, obj);
}
return obj;
}
}
}
return null;
} public static IEnumerable<T> ResolveAll<T>() where T : class
{
return ResolveAll(typeof (T)) as IEnumerable<T>;
} public static object ResolveAll(this Type type)
{
var attrs = type.GetCustomAttributes(typeof (UnityInjectionAttribute), true) as UnityInjectionAttribute[];
if (attrs != null && attrs.Length > 0)
{
var attr = attrs[0];
var unitySection = attr.GetUnityConfigurationSection();
if (unitySection != null)
{
var container = new UnityContainer().LoadConfiguration(unitySection,
string.IsNullOrEmpty(attr.Container) ? unitySection.Containers.Default.Name : attr.Container);
return container.ResolveAll(type);
}
}
return null;
}
}
} 2.
using System;
using System.Configuration;
using System.IO;
using Microsoft.Practices.Unity.Configuration; namespace Zhang.Test.ELUnityUtility
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class UnityInjectionAttribute : Attribute
{
public UnityInjectionAttribute(string Container)
{
this.Container = Container;
} public string Container { get; set; }
public string ConfigFile { get; set; }
public string Name { get; set; } public UnityConfigurationSection GetUnityConfigurationSection()
{
if (!string.IsNullOrEmpty(ConfigFile))
{
var fileMap = new ExeConfigurationFileMap
{
ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFile)
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
return configuration == null
? null
: configuration.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;
} return ConfigurationManager.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;
}
} [AttributeUsage(AttributeTargets.Class)]
public class ELPolicyinjectionAttribute : Attribute
{
public string Name { get; set; }
}
}
Unity在WPF中的应用的更多相关文章
- Unity3D 将 Unity 嵌入WPF中的一些研究笔记
一. 在 WPF 中使用 WebBrowser,直接打开 WebPlayer.html 以这种方式有一个问题是. 无法在 WebBrowser 的上面 放置其它的控件, 在运行时,都不会显示 . 以 ...
- 【Unity游戏开发】浅谈Unity游戏开发中的单元测试
一.单元测试的定义与作用 单元测试定义:单元测试在传统软件开发中是非常重要的工具,它是指对软件中的最小可测试单元进行检查和验证,一般情况下就是对代码中的一个函数去进行验证,检查它的正确性.一个单元测试 ...
- WPF中添加Winform用户自定义控件
过程:创建WPF工程->创建Winform用户自定义控件工程->WPF中引用控件->添加到Xaml页面 1.首先在WPF工程的解决方案上右击选择添加新建项目: 选择Windows窗体 ...
- 在WPF中使用依赖注入的方式创建视图
在WPF中使用依赖注入的方式创建视图 0x00 问题的产生 互联网时代桌面开发真是越来越少了,很多应用都转到了浏览器端和移动智能终端,相应的软件开发上的新技术应用到桌面开发的文章也很少.我之前主要做W ...
- MVVM模式解析和在WPF中的实现(六) 用依赖注入的方式配置ViewModel并注册消息
MVVM模式解析和在WPF中的实现(六) 用依赖注入的方式配置ViewModel并注册消息 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二 ...
- MVVM模式解析和在WPF中的实现(五)View和ViewModel的通信
MVVM模式解析和在WPF中的实现(五) View和ViewModel的通信 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 M ...
- MVVM设计模式和WPF中的实现(四)事件绑定
MVVM设计模式和在WPF中的实现(四) 事件绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
- MVVM模式解析和在WPF中的实现(三)命令绑定
MVVM模式解析和在WPF中的实现(三) 命令绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
- MVVM模式和在WPF中的实现(二)数据绑定
MVVM模式解析和在WPF中的实现(二) 数据绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
随机推荐
- Ubuntu 14.04 下安装 OpenCV
参考: Installation in Linux Error compiling OpenCV, fatal error: stdlib.h: No such file or directory 图 ...
- 【转】 ISP-黑电平校正(BLC)
转自:https://blog.csdn.net/xiaoyouck/article/details/72824534 介绍黑电平(Black Level Correction)也就是黑色的最低点,以 ...
- net基础运算符
1.Convert类型转换 总结: 类型如果相兼容的两个变量,可以使用自动类型转换或者强制类型转换. 但是,如果两个类型的变量不兼容,比如string与int或者string 与doub ...
- vue轮播,vue-awesome-swiper动态数据渲染,loop无效,轮循无效
解决办法:在渲染数组数据前.判断是否为空 v-if="slideList.length>1" <template> <div class="ban ...
- MapReduce的倒排索引
MapReduce的倒排索引 索引: 什么是索引:索引(Index)是帮助数据库高效获取数据的数据结构.索引是在基于数据库表创建的,它包含一个表中某些列的值以及记录对应的地址,并且把这些值存储在一个数 ...
- CSS3 Transform的perspective属性
以下两行语句有什么区别? Css <div id="animateTest" style="-webkit-transform: perspective(400px ...
- Linux中的#和$区别
[#]代表 root权限[$]代表普通用户
- 【转载】关于nginx以及内核参数的配置
nginx应用总结(2)--突破高并发的性能优化 原文地址:https://www.cnblogs.com/kevingrace/p/6094007.html 在日常的运维工作中,经常会用到ngin ...
- C语言冒泡(起泡)排序与选择排序的循环条件区别
冒泡排序(写法1): i = 0; i < n-1; ++i{ flag = true; j = 0; j < n-1-i; ++j{//从前面开始冒泡 if( arr[j] < a ...
- 2.2使用urllib的简单传输
使用urllib传输文件 from urllib.request import urlopen filename = 'new_1.py' password = 'password' #如果设置密码 ...