首页 > 其他 > 详细

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

时间:2014-02-27 03:42:47      阅读:465      评论:0      收藏:0      [点我收藏+]

框架解释:

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
    {}




WCF 使用 Entity Framework 配合 Unity 进行 IOC AOP 的实现,布布扣,bubuko.com

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

原文:http://blog.csdn.net/gavin_luo/article/details/19944331

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!