框架解释:
WCF 用来对我的应用提供业务处理
Entity Framework 作为 WCF 服务层的数据访问
在Entity Framework 中,我们会使用UnitOfWork 来做为事务控制
我们利用IOC构造创建我们的 DBContext ,保证 CRUD中的DBContext 和 UnitOfWork中的 DBContext 是同一个实例
然后用AOP实现业务层的切面编程
插件:
在使用Unity 进行WCF 依赖注入的时候,我使用了unity.wcf 插件,NuGet可以直接获取到,然后在业务层使用标签方法对业务类进行拦截
关键代码:
在应用unity.wcf的时候,自动生成了一个WcfServiceFactory类,里面写Unity容器的构造
public class WcfServiceFactory : UnityServiceHostFactory
{
protected override void ConfigureContainer(IUnityContainer container)
{
container.RegisterType<IService1, Service1>()
.RegisterType<IBaseDataBLL, BaseDataBLL>()
.RegisterType<IDbContextFactory, DbContextFactory<DEMOContext>>(new HttpRequestLifetimeManager());
container.AddNewExtension<Interception>();
container.Configure<Interception>().SetInterceptorFor<IBaseDataBLL>(new InterfaceInterceptor());
}
}
/// <summary>
/// 同一个http请求下只实例化一个对象
/// </summary>
internal class HttpRequestLifetimeManager : LifetimeManager
{
private readonly Guid key;
public HttpRequestLifetimeManager()
{
key = Guid.NewGuid();
}
public override object GetValue()
{
return HttpContext.Current.Items[key];
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[key] = newValue;
}
public override void RemoveValue()
{
HttpContext.Current.Items.Remove(key);
}
}
在业务层创建拦截标签
public class MyHandler : ICallHandler
{
public int Order { get; set; }//这是ICallHandler的成员,表示执行顺序
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
//这之前插入方法执行前的处理
IMethodReturn retvalue = getNext()(input, getNext);//在这里执行方法
return retvalue;
}
}
public class MyHandlerAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new MyHandler();//返回MyHandler
}
}
[MyHandler]
public class BaseDataBLL : IBaseDataBLL
{}