WCF 使用 Entity Framework 配合 Unity 进行 IOC AOP 的实现

框架解释:

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标签即可

[MyHandler]
    public class BaseDataBLL : IBaseDataBLL
    {}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值